From d929caa9150588da918badfc7d7d62070f2afd51 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 10 Sep 2025 18:58:05 +0000 Subject: [PATCH 1/2] Initial plan From 75b1eea1a68e86ce39448bb5a11c642b427db3ab Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 10 Sep 2025 19:06:24 +0000 Subject: [PATCH 2/2] Complete Java Practice Program implementation with progression from Simple to Complex Co-authored-by: ShyamSadatkar <156830588+ShyamSadatkar@users.noreply.github.com> --- .gitignore | 41 ++++++ Complex/compile.sh | 10 ++ Complex/src/AdvancedAlgorithms.java | 179 +++++++++++++++++++++++++ Complex/src/DesignPatterns.java | 156 +++++++++++++++++++++ Complex/src/MultithreadingExample.java | 117 ++++++++++++++++ Medium/compile.sh | 10 ++ Medium/src/ArraysAndCollections.java | 89 ++++++++++++ Medium/src/FileHandling.java | 82 +++++++++++ Medium/src/Student.java | 89 ++++++++++++ README.md | 139 ++++++++++++++++++- Simple/compile.sh | 12 ++ Simple/src/BasicCalculator.java | 39 ++++++ Simple/src/ConditionalStatements.java | 52 +++++++ Simple/src/HelloWorld.java | 11 ++ Simple/src/Loops.java | 57 ++++++++ Simple/src/Variables.java | 35 +++++ 16 files changed, 1116 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100755 Complex/compile.sh create mode 100644 Complex/src/AdvancedAlgorithms.java create mode 100644 Complex/src/DesignPatterns.java create mode 100644 Complex/src/MultithreadingExample.java create mode 100755 Medium/compile.sh create mode 100644 Medium/src/ArraysAndCollections.java create mode 100644 Medium/src/FileHandling.java create mode 100644 Medium/src/Student.java create mode 100755 Simple/compile.sh create mode 100644 Simple/src/BasicCalculator.java create mode 100644 Simple/src/ConditionalStatements.java create mode 100644 Simple/src/HelloWorld.java create mode 100644 Simple/src/Loops.java create mode 100644 Simple/src/Variables.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..141a52b --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Compiled class files +*.class + +# Package files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Virtual machine crash logs +hs_err_pid* + +# IDE specific files +.idea/ +*.iml +.vscode/ +.settings/ +.project +.classpath + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Temporary files +*.tmp +*.temp +student_data.txt + +# Build directories +bin/ +build/ +target/ \ No newline at end of file diff --git a/Complex/compile.sh b/Complex/compile.sh new file mode 100755 index 0000000..994e462 --- /dev/null +++ b/Complex/compile.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Compile script for Complex level programs + +echo "Compiling Complex level Java programs..." +cd src +javac *.java +echo "Compilation complete! You can now run:" +echo " java MultithreadingExample" +echo " java DesignPatterns" +echo " java AdvancedAlgorithms" \ No newline at end of file diff --git a/Complex/src/AdvancedAlgorithms.java b/Complex/src/AdvancedAlgorithms.java new file mode 100644 index 0000000..6c585ae --- /dev/null +++ b/Complex/src/AdvancedAlgorithms.java @@ -0,0 +1,179 @@ +/** + * Complex Program 3: Advanced Algorithms + * Description: Implements sorting algorithms, binary search, and recursive solutions + * Concepts: Algorithms, recursion, time complexity, searching and sorting + */ +import java.util.Arrays; +import java.util.Random; + +public class AdvancedAlgorithms { + + // Quick Sort Algorithm + public static void quickSort(int[] arr, int low, int high) { + if (low < high) { + int pivotIndex = partition(arr, low, high); + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } + } + + private static int partition(int[] arr, int low, int high) { + int pivot = arr[high]; + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] <= pivot) { + i++; + swap(arr, i, j); + } + } + swap(arr, i + 1, high); + return i + 1; + } + + private static void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + // Merge Sort Algorithm + public static void mergeSort(int[] arr, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + mergeSort(arr, left, mid); + mergeSort(arr, mid + 1, right); + merge(arr, left, mid, right); + } + } + + private static void merge(int[] arr, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + + int[] leftArr = new int[n1]; + int[] rightArr = new int[n2]; + + System.arraycopy(arr, left, leftArr, 0, n1); + System.arraycopy(arr, mid + 1, rightArr, 0, n2); + + int i = 0, j = 0, k = left; + + while (i < n1 && j < n2) { + if (leftArr[i] <= rightArr[j]) { + arr[k] = leftArr[i]; + i++; + } else { + arr[k] = rightArr[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = leftArr[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = rightArr[j]; + j++; + k++; + } + } + + // Binary Search Algorithm + public static int binarySearch(int[] arr, int target) { + int left = 0, right = arr.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; + } + + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; // Element not found + } + + // Fibonacci using recursion with memoization + private static long[] fibMemo = new long[100]; + + public static long fibonacci(int n) { + if (n <= 1) { + return n; + } + + if (fibMemo[n] != 0) { + return fibMemo[n]; + } + + fibMemo[n] = fibonacci(n - 1) + fibonacci(n - 2); + return fibMemo[n]; + } + + // Tower of Hanoi recursive solution + public static void towerOfHanoi(int n, char source, char destination, char auxiliary) { + if (n == 1) { + System.out.println("Move disk 1 from " + source + " to " + destination); + return; + } + + towerOfHanoi(n - 1, source, auxiliary, destination); + System.out.println("Move disk " + n + " from " + source + " to " + destination); + towerOfHanoi(n - 1, auxiliary, destination, source); + } + + public static void main(String[] args) { + System.out.println("=== Advanced Algorithms Example ==="); + + // Generate random array for sorting + Random random = new Random(); + int[] originalArray = new int[10]; + for (int i = 0; i < originalArray.length; i++) { + originalArray[i] = random.nextInt(100); + } + + System.out.println("Original Array: " + Arrays.toString(originalArray)); + + // Quick Sort Demo + int[] quickSortArray = originalArray.clone(); + long startTime = System.nanoTime(); + quickSort(quickSortArray, 0, quickSortArray.length - 1); + long quickSortTime = System.nanoTime() - startTime; + System.out.println("Quick Sort Result: " + Arrays.toString(quickSortArray)); + System.out.println("Quick Sort Time: " + quickSortTime + " nanoseconds"); + + // Merge Sort Demo + int[] mergeSortArray = originalArray.clone(); + startTime = System.nanoTime(); + mergeSort(mergeSortArray, 0, mergeSortArray.length - 1); + long mergeSortTime = System.nanoTime() - startTime; + System.out.println("Merge Sort Result: " + Arrays.toString(mergeSortArray)); + System.out.println("Merge Sort Time: " + mergeSortTime + " nanoseconds"); + + // Binary Search Demo + int target = quickSortArray[5]; // Pick a random element + int index = binarySearch(quickSortArray, target); + System.out.println("\nBinary Search for " + target + ": Found at index " + index); + + // Fibonacci Demo + System.out.println("\nFibonacci Sequence (first 15 numbers):"); + for (int i = 0; i < 15; i++) { + System.out.print(fibonacci(i) + " "); + } + System.out.println(); + + // Tower of Hanoi Demo + System.out.println("\nTower of Hanoi (3 disks):"); + towerOfHanoi(3, 'A', 'C', 'B'); + } +} \ No newline at end of file diff --git a/Complex/src/DesignPatterns.java b/Complex/src/DesignPatterns.java new file mode 100644 index 0000000..17c19f7 --- /dev/null +++ b/Complex/src/DesignPatterns.java @@ -0,0 +1,156 @@ +/** + * Complex Program 2: Design Patterns - Singleton and Factory + * Description: Demonstrates Singleton and Factory design patterns + * Concepts: Design patterns, thread-safe singleton, factory method pattern + */ + +// Singleton Pattern - Database Connection +class DatabaseConnection { + private static volatile DatabaseConnection instance; + private String connectionString; + + // Private constructor to prevent instantiation + private DatabaseConnection() { + connectionString = "jdbc:mysql://localhost:3306/testdb"; + System.out.println("Database connection created!"); + } + + // Thread-safe singleton implementation + public static DatabaseConnection getInstance() { + if (instance == null) { + synchronized (DatabaseConnection.class) { + if (instance == null) { + instance = new DatabaseConnection(); + } + } + } + return instance; + } + + public void connect() { + System.out.println("Connected to: " + connectionString); + } + + public void disconnect() { + System.out.println("Disconnected from database"); + } +} + +// Factory Pattern - Shape Factory +abstract class Shape { + protected String color; + + public Shape(String color) { + this.color = color; + } + + public abstract void draw(); + public abstract double getArea(); +} + +class Circle extends Shape { + private double radius; + + public Circle(String color, double radius) { + super(color); + this.radius = radius; + } + + @Override + public void draw() { + System.out.println("Drawing " + color + " circle with radius: " + radius); + } + + @Override + public double getArea() { + return Math.PI * radius * radius; + } +} + +class Rectangle extends Shape { + private double width, height; + + public Rectangle(String color, double width, double height) { + super(color); + this.width = width; + this.height = height; + } + + @Override + public void draw() { + System.out.println("Drawing " + color + " rectangle " + width + "x" + height); + } + + @Override + public double getArea() { + return width * height; + } +} + +class Triangle extends Shape { + private double base, height; + + public Triangle(String color, double base, double height) { + super(color); + this.base = base; + this.height = height; + } + + @Override + public void draw() { + System.out.println("Drawing " + color + " triangle with base: " + base + ", height: " + height); + } + + @Override + public double getArea() { + return 0.5 * base * height; + } +} + +class ShapeFactory { + public static Shape createShape(String shapeType, String color, double... dimensions) { + switch (shapeType.toLowerCase()) { + case "circle": + return new Circle(color, dimensions[0]); + case "rectangle": + return new Rectangle(color, dimensions[0], dimensions[1]); + case "triangle": + return new Triangle(color, dimensions[0], dimensions[1]); + default: + throw new IllegalArgumentException("Unknown shape type: " + shapeType); + } + } +} + +public class DesignPatterns { + public static void main(String[] args) { + System.out.println("=== Design Patterns Example ==="); + + // Singleton Pattern Demo + System.out.println("\n1. Singleton Pattern:"); + DatabaseConnection db1 = DatabaseConnection.getInstance(); + DatabaseConnection db2 = DatabaseConnection.getInstance(); + + System.out.println("Same instance? " + (db1 == db2)); + db1.connect(); + db2.disconnect(); + + // Factory Pattern Demo + System.out.println("\n2. Factory Pattern:"); + try { + Shape circle = ShapeFactory.createShape("circle", "Red", 5.0); + Shape rectangle = ShapeFactory.createShape("rectangle", "Blue", 4.0, 6.0); + Shape triangle = ShapeFactory.createShape("triangle", "Green", 3.0, 4.0); + + Shape[] shapes = {circle, rectangle, triangle}; + + for (Shape shape : shapes) { + shape.draw(); + System.out.println("Area: " + String.format("%.2f", shape.getArea())); + System.out.println(); + } + } catch (IllegalArgumentException e) { + System.out.println("Error: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/Complex/src/MultithreadingExample.java b/Complex/src/MultithreadingExample.java new file mode 100644 index 0000000..9ef8f3d --- /dev/null +++ b/Complex/src/MultithreadingExample.java @@ -0,0 +1,117 @@ +/** + * Complex Program 1: Multithreading + * Description: Demonstrates thread creation, synchronization, and concurrent execution + * Concepts: Thread class, Runnable interface, synchronization, thread safety + */ + +// Producer class that extends Thread +class Producer extends Thread { + private SharedBuffer buffer; + private int producerId; + + public Producer(SharedBuffer buffer, int producerId) { + this.buffer = buffer; + this.producerId = producerId; + } + + @Override + public void run() { + for (int i = 1; i <= 5; i++) { + try { + buffer.produce(producerId * 10 + i); + Thread.sleep(1000); // Simulate production time + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } +} + +// Consumer class that implements Runnable +class Consumer implements Runnable { + private SharedBuffer buffer; + private int consumerId; + + public Consumer(SharedBuffer buffer, int consumerId) { + this.buffer = buffer; + this.consumerId = consumerId; + } + + @Override + public void run() { + for (int i = 0; i < 5; i++) { + try { + buffer.consume(consumerId); + Thread.sleep(1500); // Simulate consumption time + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } +} + +// Shared buffer with synchronization +class SharedBuffer { + private int buffer; + private boolean hasData = false; + + public synchronized void produce(int data) throws InterruptedException { + while (hasData) { + wait(); // Wait if buffer is full + } + buffer = data; + hasData = true; + System.out.println("Produced: " + data + " by " + Thread.currentThread().getName()); + notifyAll(); // Notify waiting consumers + } + + public synchronized int consume(int consumerId) throws InterruptedException { + while (!hasData) { + wait(); // Wait if buffer is empty + } + int data = buffer; + hasData = false; + System.out.println("Consumed: " + data + " by Consumer-" + consumerId); + notifyAll(); // Notify waiting producers + return data; + } +} + +public class MultithreadingExample { + public static void main(String[] args) { + System.out.println("=== Multithreading Example ==="); + + SharedBuffer buffer = new SharedBuffer(); + + // Create producer threads + Producer producer1 = new Producer(buffer, 1); + Producer producer2 = new Producer(buffer, 2); + producer1.setName("Producer-1"); + producer2.setName("Producer-2"); + + // Create consumer threads + Thread consumer1 = new Thread(new Consumer(buffer, 1)); + Thread consumer2 = new Thread(new Consumer(buffer, 2)); + consumer1.setName("Consumer-1"); + consumer2.setName("Consumer-2"); + + // Start threads + System.out.println("Starting threads..."); + producer1.start(); + producer2.start(); + consumer1.start(); + consumer2.start(); + + try { + // Wait for all threads to complete + producer1.join(); + producer2.join(); + consumer1.join(); + consumer2.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + System.out.println("All threads completed!"); + } +} \ No newline at end of file diff --git a/Medium/compile.sh b/Medium/compile.sh new file mode 100755 index 0000000..33353fd --- /dev/null +++ b/Medium/compile.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Compile script for Medium level programs + +echo "Compiling Medium level Java programs..." +cd src +javac *.java +echo "Compilation complete! You can now run:" +echo " java Student" +echo " java ArraysAndCollections" +echo " java FileHandling" \ No newline at end of file diff --git a/Medium/src/ArraysAndCollections.java b/Medium/src/ArraysAndCollections.java new file mode 100644 index 0000000..c728f2f --- /dev/null +++ b/Medium/src/ArraysAndCollections.java @@ -0,0 +1,89 @@ +/** + * Medium Program 2: Arrays and Collections + * Description: Demonstrates arrays and ArrayList operations + * Concepts: Arrays, ArrayList, collections framework, iteration + */ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +public class ArraysAndCollections { + public static void main(String[] args) { + System.out.println("=== Arrays and Collections Example ==="); + + // 1. Regular Arrays + System.out.println("\n1. Regular Arrays:"); + int[] numbers = {5, 2, 8, 1, 9, 3}; + System.out.println("Original array: " + Arrays.toString(numbers)); + + // Array operations + Arrays.sort(numbers); + System.out.println("Sorted array: " + Arrays.toString(numbers)); + + int sum = 0; + for (int num : numbers) { + sum += num; + } + System.out.println("Sum of elements: " + sum); + System.out.println("Average: " + (sum / (double) numbers.length)); + + // 2. ArrayList + System.out.println("\n2. ArrayList:"); + ArrayList fruits = new ArrayList<>(); + + // Adding elements + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Orange"); + fruits.add("Mango"); + System.out.println("Fruits list: " + fruits); + + // ArrayList operations + fruits.add(1, "Grapes"); // Insert at index 1 + System.out.println("After insertion: " + fruits); + + fruits.remove("Banana"); + System.out.println("After removal: " + fruits); + + Collections.sort(fruits); + System.out.println("Sorted fruits: " + fruits); + + // 3. ArrayList with Integer + System.out.println("\n3. ArrayList with Numbers:"); + ArrayList scores = new ArrayList<>(); + scores.addAll(Arrays.asList(85, 92, 78, 96, 88, 75, 90)); + System.out.println("Scores: " + scores); + + // Find max, min, average + int maxScore = Collections.max(scores); + int minScore = Collections.min(scores); + double average = scores.stream().mapToInt(Integer::intValue).average().orElse(0.0); + + System.out.println("Max score: " + maxScore); + System.out.println("Min score: " + minScore); + System.out.println("Average score: " + String.format("%.2f", average)); + + // 4. 2D Array + System.out.println("\n4. 2D Array (Matrix):"); + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + + System.out.println("Matrix:"); + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[i].length; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + + // Find sum of diagonal elements + int diagonalSum = 0; + for (int i = 0; i < matrix.length; i++) { + diagonalSum += matrix[i][i]; + } + System.out.println("Diagonal sum: " + diagonalSum); + } +} \ No newline at end of file diff --git a/Medium/src/FileHandling.java b/Medium/src/FileHandling.java new file mode 100644 index 0000000..52ff275 --- /dev/null +++ b/Medium/src/FileHandling.java @@ -0,0 +1,82 @@ +/** + * Medium Program 3: File Handling + * Description: Demonstrates file reading, writing, and handling + * Concepts: FileWriter, FileReader, BufferedReader, exception handling + */ +import java.io.*; +import java.util.Scanner; + +public class FileHandling { + private static final String FILE_NAME = "student_data.txt"; + + public static void main(String[] args) { + System.out.println("=== File Handling Example ==="); + + // Write data to file + writeToFile(); + + // Read data from file + readFromFile(); + + // Append data to file + appendToFile(); + + // Read updated file + System.out.println("\nAfter appending:"); + readFromFile(); + + // Clean up - delete the file + deleteFile(); + } + + // Method to write data to file + public static void writeToFile() { + try (FileWriter writer = new FileWriter(FILE_NAME)) { + writer.write("Student Records\n"); + writer.write("================\n"); + writer.write("1. John Doe - Computer Science - GPA: 3.8\n"); + writer.write("2. Jane Smith - Mathematics - GPA: 3.9\n"); + writer.write("3. Bob Johnson - Physics - GPA: 3.6\n"); + System.out.println("Data written to file successfully!"); + } catch (IOException e) { + System.out.println("Error writing to file: " + e.getMessage()); + } + } + + // Method to read data from file + public static void readFromFile() { + try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) { + System.out.println("\nReading from file:"); + System.out.println("==================="); + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + } catch (FileNotFoundException e) { + System.out.println("File not found: " + e.getMessage()); + } catch (IOException e) { + System.out.println("Error reading file: " + e.getMessage()); + } + } + + // Method to append data to file + public static void appendToFile() { + try (FileWriter writer = new FileWriter(FILE_NAME, true)) { + writer.write("4. Alice Brown - Chemistry - GPA: 3.7\n"); + writer.write("5. Charlie Davis - Biology - GPA: 3.5\n"); + System.out.println("Data appended to file successfully!"); + } catch (IOException e) { + System.out.println("Error appending to file: " + e.getMessage()); + } + } + + // Method to delete file + public static void deleteFile() { + File file = new File(FILE_NAME); + if (file.delete()) { + System.out.println("\nFile deleted successfully!"); + } else { + System.out.println("\nFailed to delete file!"); + } + } +} \ No newline at end of file diff --git a/Medium/src/Student.java b/Medium/src/Student.java new file mode 100644 index 0000000..f30ab78 --- /dev/null +++ b/Medium/src/Student.java @@ -0,0 +1,89 @@ +/** + * Medium Program 1: Class and Objects (OOP Basics) + * Description: Demonstrates basic Object-Oriented Programming concepts + * Concepts: Classes, objects, constructors, methods, encapsulation + */ +public class Student { + // Private instance variables (encapsulation) + private String name; + private int age; + private String course; + private double gpa; + + // Default constructor + public Student() { + this.name = "Unknown"; + this.age = 0; + this.course = "Not Assigned"; + this.gpa = 0.0; + } + + // Parameterized constructor + public Student(String name, int age, String course, double gpa) { + this.name = name; + this.age = age; + this.course = course; + this.gpa = gpa; + } + + // Getter methods + public String getName() { return name; } + public int getAge() { return age; } + public String getCourse() { return course; } + public double getGpa() { return gpa; } + + // Setter methods + public void setName(String name) { this.name = name; } + public void setAge(int age) { this.age = age; } + public void setCourse(String course) { this.course = course; } + public void setGpa(double gpa) { this.gpa = gpa; } + + // Method to display student information + public void displayInfo() { + System.out.println("=== Student Information ==="); + System.out.println("Name: " + name); + System.out.println("Age: " + age); + System.out.println("Course: " + course); + System.out.println("GPA: " + gpa); + System.out.println("Status: " + getStatus()); + } + + // Method to determine academic status + public String getStatus() { + if (gpa >= 3.5) { + return "Excellent"; + } else if (gpa >= 3.0) { + return "Good"; + } else if (gpa >= 2.0) { + return "Average"; + } else { + return "Needs Improvement"; + } + } + + // Main method to test the class + public static void main(String[] args) { + // Create objects using different constructors + Student student1 = new Student(); + Student student2 = new Student("Alice Johnson", 20, "Computer Science", 3.8); + + System.out.println("=== Object-Oriented Programming Example ==="); + + // Display default student + System.out.println("\nDefault Student:"); + student1.displayInfo(); + + // Display parameterized student + System.out.println("\nParameterized Student:"); + student2.displayInfo(); + + // Modify student1 using setter methods + student1.setName("Bob Smith"); + student1.setAge(19); + student1.setCourse("Mathematics"); + student1.setGpa(3.2); + + System.out.println("\nModified Student:"); + student1.displayInfo(); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 789ab8a..81876c5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,137 @@ -# Java-Practice-Program -Simple to Complex Program +# Java Practice Programs +**Time to practice from Simple to Complex** + +This repository contains a structured collection of Java programming examples that progress from simple to complex concepts. Perfect for beginners learning Java or experienced developers reviewing core concepts. + +## 📁 Repository Structure + +``` +Java-Practice-Program/ +├── Simple/ # Basic Java concepts +│ └── src/ +├── Medium/ # Intermediate concepts (OOP, Collections) +│ └── src/ +├── Complex/ # Advanced concepts (Multithreading, Design Patterns) +│ └── src/ +└── README.md +``` + +## 🎯 Learning Path + +### 🟢 Simple Level +Start here if you're new to Java or need to review basics. + +| Program | Concepts Covered | Description | +|---------|------------------|-------------| +| `HelloWorld.java` | Basic syntax, main method, println | Your first Java program | +| `Variables.java` | Data types, variable declaration | Working with different data types | +| `BasicCalculator.java` | Arithmetic operators, user input | Interactive calculator | +| `ConditionalStatements.java` | if-else, comparison operators | Grade calculator with conditions | +| `Loops.java` | for, while, do-while loops | Different loop types and patterns | + +### 🟡 Medium Level +Progress here once you're comfortable with basic syntax. + +| Program | Concepts Covered | Description | +|---------|------------------|-------------| +| `Student.java` | Classes, objects, constructors, encapsulation | OOP fundamentals with student management | +| `ArraysAndCollections.java` | Arrays, ArrayList, Collections framework | Data structures and operations | +| `FileHandling.java` | File I/O, exception handling | Reading from and writing to files | + +### 🔴 Complex Level +Advanced topics for experienced developers. + +| Program | Concepts Covered | Description | +|---------|------------------|-------------| +| `MultithreadingExample.java` | Threads, synchronization, producer-consumer | Concurrent programming | +| `DesignPatterns.java` | Singleton, Factory patterns | Common design patterns | +| `AdvancedAlgorithms.java` | Sorting, searching, recursion | Algorithm implementations | + +## 🚀 How to Run + +### Prerequisites +- Java Development Kit (JDK) 8 or higher +- Command line access + +### Compilation and Execution + +#### For Simple Programs: +```bash +cd Simple/src +javac *.java +java HelloWorld +java Variables +java BasicCalculator +java ConditionalStatements +java Loops +``` + +#### For Medium Programs: +```bash +cd Medium/src +javac *.java +java Student +java ArraysAndCollections +java FileHandling +``` + +#### For Complex Programs: +```bash +cd Complex/src +javac *.java +java MultithreadingExample +java DesignPatterns +java AdvancedAlgorithms +``` + +## 📚 What You'll Learn + +### Simple Level +- ✅ Java syntax and structure +- ✅ Variables and data types +- ✅ User input and output +- ✅ Conditional statements +- ✅ Loop constructs +- ✅ Basic arithmetic operations + +### Medium Level +- ✅ Object-Oriented Programming (OOP) +- ✅ Classes, objects, and methods +- ✅ Constructors and encapsulation +- ✅ Arrays and dynamic collections +- ✅ File input/output operations +- ✅ Exception handling + +### Complex Level +- ✅ Multithreading and synchronization +- ✅ Thread-safe programming +- ✅ Design patterns (Singleton, Factory) +- ✅ Advanced algorithms (sorting, searching) +- ✅ Recursion and memoization +- ✅ Performance considerations + +## 🎓 Learning Tips + +1. **Start with Simple**: Master basic concepts before moving to complex topics +2. **Practice Regularly**: Code along with each example +3. **Experiment**: Modify the programs to see how changes affect behavior +4. **Understand, Don't Memorize**: Focus on understanding concepts rather than memorizing syntax +5. **Build Projects**: Use these concepts to create your own projects + +## 🤝 Contributing + +Feel free to contribute by: +- Adding new practice programs +- Improving existing code +- Adding more detailed comments +- Fixing bugs or issues + +## 📄 License + +This project is for educational purposes. Feel free to use, modify, and share! + +--- + +**Happy Coding! 🚀** + +*"The journey of a thousand miles begins with a single step" - Start with Simple, progress to Complex!* diff --git a/Simple/compile.sh b/Simple/compile.sh new file mode 100755 index 0000000..abb453a --- /dev/null +++ b/Simple/compile.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# Compile script for Simple level programs + +echo "Compiling Simple level Java programs..." +cd src +javac *.java +echo "Compilation complete! You can now run:" +echo " java HelloWorld" +echo " java Variables" +echo " java BasicCalculator" +echo " java ConditionalStatements" +echo " java Loops" \ No newline at end of file diff --git a/Simple/src/BasicCalculator.java b/Simple/src/BasicCalculator.java new file mode 100644 index 0000000..fec135f --- /dev/null +++ b/Simple/src/BasicCalculator.java @@ -0,0 +1,39 @@ +/** + * Simple Program 3: Basic Calculator + * Description: Performs basic arithmetic operations + * Concepts: arithmetic operators, variables, user input + */ +import java.util.Scanner; + +public class BasicCalculator { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.println("=== Basic Calculator ==="); + System.out.print("Enter first number: "); + double num1 = scanner.nextDouble(); + + System.out.print("Enter second number: "); + double num2 = scanner.nextDouble(); + + // Perform calculations + double addition = num1 + num2; + double subtraction = num1 - num2; + double multiplication = num1 * num2; + double division = num1 / num2; + + // Display results + System.out.println("\n=== Results ==="); + System.out.println(num1 + " + " + num2 + " = " + addition); + System.out.println(num1 + " - " + num2 + " = " + subtraction); + System.out.println(num1 + " * " + num2 + " = " + multiplication); + + if (num2 != 0) { + System.out.println(num1 + " / " + num2 + " = " + division); + } else { + System.out.println("Division by zero is not allowed!"); + } + + scanner.close(); + } +} \ No newline at end of file diff --git a/Simple/src/ConditionalStatements.java b/Simple/src/ConditionalStatements.java new file mode 100644 index 0000000..f4acd4f --- /dev/null +++ b/Simple/src/ConditionalStatements.java @@ -0,0 +1,52 @@ +/** + * Simple Program 4: Conditional Statements + * Description: Demonstrates if-else statements and comparison operators + * Concepts: if-else, else if, comparison operators, logical operators + */ +import java.util.Scanner; + +public class ConditionalStatements { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.println("=== Grade Calculator ==="); + System.out.print("Enter your score (0-100): "); + int score = scanner.nextInt(); + + // Determine grade using if-else statements + char grade; + String message; + + if (score >= 90) { + grade = 'A'; + message = "Excellent!"; + } else if (score >= 80) { + grade = 'B'; + message = "Good job!"; + } else if (score >= 70) { + grade = 'C'; + message = "Fair work."; + } else if (score >= 60) { + grade = 'D'; + message = "Needs improvement."; + } else { + grade = 'F'; + message = "Please study more."; + } + + // Display result + System.out.println("\n=== Result ==="); + System.out.println("Score: " + score); + System.out.println("Grade: " + grade); + System.out.println("Message: " + message); + + // Check if passing + if (score >= 60) { + System.out.println("Status: PASS"); + } else { + System.out.println("Status: FAIL"); + } + + scanner.close(); + } +} \ No newline at end of file diff --git a/Simple/src/HelloWorld.java b/Simple/src/HelloWorld.java new file mode 100644 index 0000000..ff6b33a --- /dev/null +++ b/Simple/src/HelloWorld.java @@ -0,0 +1,11 @@ +/** + * Simple Program 1: Hello World + * Description: Basic Java program to print "Hello World" + * Concepts: Basic syntax, main method, System.out.println() + */ +public class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello World!"); + System.out.println("Welcome to Java Practice Programs!"); + } +} \ No newline at end of file diff --git a/Simple/src/Loops.java b/Simple/src/Loops.java new file mode 100644 index 0000000..ddaec2b --- /dev/null +++ b/Simple/src/Loops.java @@ -0,0 +1,57 @@ +/** + * Simple Program 5: Loops + * Description: Demonstrates for, while, and do-while loops + * Concepts: for loop, while loop, do-while loop, break, continue + */ +public class Loops { + public static void main(String[] args) { + System.out.println("=== Loop Examples ==="); + + // For loop example + System.out.println("\n1. For Loop - Numbers 1 to 5:"); + for (int i = 1; i <= 5; i++) { + System.out.print(i + " "); + } + System.out.println(); + + // While loop example + System.out.println("\n2. While Loop - Even numbers 2 to 10:"); + int num = 2; + while (num <= 10) { + System.out.print(num + " "); + num += 2; + } + System.out.println(); + + // Do-while loop example + System.out.println("\n3. Do-While Loop - Countdown from 5:"); + int count = 5; + do { + System.out.print(count + " "); + count--; + } while (count > 0); + System.out.println("Go!"); + + // Nested loops - multiplication table + System.out.println("\n4. Nested Loops - 3x3 Multiplication Table:"); + for (int i = 1; i <= 3; i++) { + for (int j = 1; j <= 3; j++) { + System.out.print((i * j) + "\t"); + } + System.out.println(); + } + + // Loop with break and continue + System.out.println("\n5. Loop with Break and Continue:"); + for (int i = 1; i <= 10; i++) { + if (i == 5) { + continue; // Skip 5 + } + if (i == 8) { + break; // Stop at 8 + } + System.out.print(i + " "); + } + System.out.println(); + } +} \ No newline at end of file diff --git a/Simple/src/Variables.java b/Simple/src/Variables.java new file mode 100644 index 0000000..8b0ecad --- /dev/null +++ b/Simple/src/Variables.java @@ -0,0 +1,35 @@ +/** + * Simple Program 2: Variables and Data Types + * Description: Demonstrates different data types and variables + * Concepts: int, double, char, boolean, String, variable declaration + */ +public class Variables { + public static void main(String[] args) { + // Integer variables + int age = 25; + int year = 2024; + + // Double variables + double price = 99.99; + double pi = 3.14159; + + // Character variable + char grade = 'A'; + + // Boolean variable + boolean isStudent = true; + + // String variable + String name = "John Doe"; + + // Display all variables + System.out.println("=== Variable Examples ==="); + System.out.println("Name: " + name); + System.out.println("Age: " + age + " years"); + System.out.println("Year: " + year); + System.out.println("Price: $" + price); + System.out.println("Pi value: " + pi); + System.out.println("Grade: " + grade); + System.out.println("Is Student: " + isStudent); + } +} \ No newline at end of file