Skip to content

This repository serves as a record of my Java learning journey.

License

Notifications You must be signed in to change notification settings

TORRYNN/Java_Learning

Repository files navigation

torrynntorrynntorrynn

☕️ Java Basics Repository ☕️

Welcome to the Java Repository, your comprehensive guide to learning Java programming! 📚✨

torrynn🤔 Why this repository?

This repository serves as a record of my Java learning journey. It includes various Java programs that I've implemented to practice and solidify my understanding of fundamental concepts. While primarily for personal use, this repository can also benefit beginners looking to explore Java programming

torrynn📝 Prerequisites

efore you begin, make sure you have the following installed on your machine:

  • Java JDK (Java Development Kit)
  • Your favorite Integrated Development Environment (IDE) such as:
    • IntelliJ IDEA
    • Eclipse
    • NetBeans
    • Visual Studio Code

Ensure these software tools are set up and ready to use before proceeding with the exercises.

torrynn📝 How to Use

Running the Programs

  1. Clone this repository to your local machine.
  2. Navigate to the directory where you cloned the repository.
  3. Open any Java file using a text editor or an IDE.
  4. Compile and run the program using your preferred Java compiler or IDE.

torrynn📂Table of Contents

📂 10_Variable_and_DateType
  • 📄 Question1.java: This program takes three numbers (A, B, and C) as input and calculates their average. It then outputs the calculated average to the console.
  • 📄 Question2.java: This program calculates the area of a square given the length of its side.
  • 📄 Question3.java: This program calculates the final price of items (pencil, pen, and eraser) including an 18% GST (Goods and Services Tax).
  • 📄 Question4.java: This program demonstrates the use of different primitive data types (byte, char, short, int, float, double) in Java and performs a calculation using these variables.
📂 11_Conditional_Statements
  • 📄 Question1.java: This program takes a number from the user and prints whether it is positive or negative.
  • 📄 Question2.java: This program checks if a given temperature (temp) is greater than 100 degrees Fahrenheit and prints "You have a fever" if true, otherwise prints "You do not have a fever".
  • 📄 Question3.java: This program takes a week number (1-7) from the user and prints the corresponding day of the week using a switch statement.
  • 📄 Question5.java: This program checks if a given year (var2) is a leap year using nested if statements.
📂 12_Loops
  • 📄 Question1.java: This program reads a number (num) from the user and calculates the sum of even and odd integers up to num.
  • 📄 Question2.java: This program calculates the factorial of a number (num) entered by the user using iterative multiplication.
  • 📄 Question3.java: This program prints the multiplication table of a number (num) entered by the user.
📂 12_Patterns
  • 📄 AdvancedPattern2.java: This Java program generates and prints the following patterns:

    • Pattern1:
      *
      **
      ***
      ****
      *****
      ****
      ***
      **
      *
      
    • Pattern2:
      1 2 3 4 5
       2 3 4 5
        3 4 5
         4 5
          5
         4 5
        3 4 5
       2 3 4 5
      1 2 3 4 5
      
  • 📄 AdvancePattern.java: This Java program generates and prints multiple patterns:

    • Pattern1:
      1
      11
      121
      1221
      12221
      
    • Pattern2:
      1
      232
      34543
      4567654
      567898765
      
    • Pattern3:
      1
      23
      345
      4567
      
    • Pattern4:
      *
      ***
      *****
      *******
      
    • Pattern5 (Same as Pattern3):
      1
      23
      345
      4567
      
    • Pattern6:
      1
      23
      345
      4567
      
    • Pattern7:
      1 2 3 4 5
       2 3 4 5
        3 4 5
         4 5
          5
         4 5
        3 4 5
       2 3 4 5
      1 2 3 4 5
      
    • Pattern9:
      *****
       ****
        ***
         **
          *
      
    • Pattern10:
      1
      2
      3
      4
      5
      4
      3
      2
      1
      
  • 📄 Pattern1.java: This Java program generates and prints multiple patterns based on user input n:

    • Pattern1 (Ascending *):
      *
      **
      ***
      ****
      *****
      
    • Pattern2 (Ascending numbers):
      1
      12
      123
      1234
      12345
      
    • Pattern3 (Ascending repeated numbers):
      1
      22
      333
      4444
      55555
      
    • Inverted Pattern1 (Descending *):
      *****
      ****
      ***
      **
      *
      
    • Pattern4 (Alphabetical pattern):
      A
      BC
      DEF
      GHIJ
      KLMNOP
      
    • Inverted Alphabetical pattern:
      ABCDE
      FGHI
      JK
      LMNOPQ
      RSTUVWX
      
📂 13_Methods
  • 📄 Question1.java: This Java program defines a method avg(int a, int b, int c) that calculates the average of three integers a, b, and c. It then demonstrates the usage of this method by computing and printing the averages of different sets of numbers.
  • 📄 Question2.java: This Java program defines a method isEven(int a) that checks if a given integer a is even. The method returns true if the number is even and false otherwise. The program then tests this method with different integers and prints whether each number is even or odd.
  • 📄 Question3.java: This Java program contains two overloaded methods isPalindrome to check if a given number or string is a palindrome.
    • boolean isPalindrome(int num): Checks if the integer num is a palindrome by reversing its digits and comparing it to the original number.
    • boolean isPalindrome(String str): Checks if the string str is a palindrome by comparing it to its reversed version (case insensitive). The program demonstrates the usage of these methods by testing with different inputs and printing the results.
  • 📄 Question4.java: This Java program defines a method operation that performs several mathematical operations on two integers a and b.
    • void operation(int a, int b): This method prints the minimum (Math.min), maximum (Math.max), square root (Math.sqrt) of b, b raised to the power of a (Math.pow), and the absolute value of -5.242 (Math.abs).
    • The main method demonstrates the usage of operation with values 3 and 2, showcasing these mathematical operations.
  • 📄 Question5.java: This Java program defines a method sum that calculates the sum of the digits of an integer num.
    • int sum(int num): This method iteratively calculates the sum of the digits of num using a while loop and returns the computed sum.
    • The main method demonstrates the usage of sum with the integer 811, printing the sum of its digits.
📂 16_ARRAYS (Part1)
  • 📄 BinarySearch.java: This Java program implements the binary search algorithm to find a target element in a sorted array.

  • 📄 Largestnum.java: This Java program finds the largest number in an array of integers.

  • 📄 LinearSearch.java: This Java program implements the linear search algorithm to find a target element in an array.

  • 📄 PairsArray.java: This Java program defines a method PairArray that takes an array of integers as input and prints all possible pairs of elements from the array in the format (element1, element2). The method iterates through each element in the array and pairs it with every subsequent element. In the main method, an example array { 1, 2, 3, 4 } is used to demonstrate the functionality of PairArray.

  • 📄 PrintSubArray.java: This Java program defines a method SubArray that prints all possible subarrays of an array of integers. A subarray is a contiguous portion of the array. The method uses nested loops to generate and print subarrays starting from each element of the array. For each starting index i, it iterates over all possible ending indices j and prints the elements of the subarray from i to j. After printing each subarray, it prints a new line to separate them visually. The total number of subarrays is also calculated and displayed at the end of execution. In the main method, an example array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } is used to demonstrate the functionality of the SubArray method.

  • 📄 Reverse.java: This Java program demonstrates two methods to reverse an array of integers.

    1. rev method:

      • This method iterates through the input array arr and creates a new array rev where each element is placed in reverse order. - Time Complexity (T.C): O(n), where n is the number of elements in the array. - Space Complexity (S.C): O(n) for the additional array rev.
    2. betterrev method:

      • This method employs an optimized approach to reverse the array in place, without using additional space.
      • It initializes two pointers, first at the beginning and last at the end of the array, and swaps elements until first surpasses last. - Time Complexity (T.C): O(n), where n is the number of elements in the array. - Space Complexity (S.C): O(1) as it uses only a constant amount of extra space.

    In the main method, an example array { 1, 2, 3, ..., 14 } is created and passed to both rev and betterrev methods to demonstrate their functionality. The original array and the reversed arrays are printed to the console for comparison.

📂 17_Arrays(Part2)
  • 📄 BuySellStocks.java: This program calculates the maximum profit that can be achieved by buying and selling stocks based on their prices on consecutive days. It employs a linear scan approach to track the minimum buying price (buyPrice) and compute the maximum profit (maxProfit) by comparing current prices with buyPrice.

  • 📄 MaxSubarraySum.java: This program demonstrates different approaches to find the maximum sum of contiguous subarrays within an integer array (arr):

    • maxSum: Uses nested loops to compute sums of all possible subarrays and tracks the maximum sum found.
    • maxsum1: Optimized approach using a prefix sum array to compute subarray sums efficiently.
    • kadane: Implements Kadane's Algorithm to find the maximum sum subarray in linear time, suitable for arrays with both positive and negative numbers.
    • kadane1: Enhanced version of Kadane's Algorithm that also prints the subarray with the maximum sum.
  • 📄 Question1.java: This program provides two methods to determine if an integer array (arr) contains any duplicate elements:

    • Distinct: Uses nested loops to compare each element with every other element in the array to check for duplicates. Returns true if duplicates are found, otherwise false.
      • Time Complexity: ( O(n<sup>2</sup>) )
      • Space Complexity: ( O(1) )
    • distinct: Utilizes a HashSet to store elements as they are encountered. If an element is already present in the HashSet, it indicates a duplicate and returns true. Otherwise, adds the element to the HashSet and continues. Returns false if no duplicates are found.
      • Time Complexity: ( O(n) )
      • Space Complexity: ( O(n) )
  • 📄 Question3.java: This file defines a method price to calculate the maximum profit that can be achieved from buying and selling stocks based on an integer array price[] representing daily stock prices.

    • price: Iterates through the price array to calculate the maximum profit by determining the difference between each day's price and the minimum price observed so far (stockprice). Updates stockprice and maxProfit accordingly. - Time Complexity: ( O(n) ) - Space Complexity: ( O(1) )
  • 📄 Question4.java: Placeholder description.

  • 📄 Question4.java: This file contains a method trap that calculates the amount of water trapped between bars in an elevation map represented by an integer array arr[].

    • trap: Computes the trapped water by simulating two passes over the array to determine the maximum heights to the left (leftmax) and right (rightmax) of each bar. Then calculates the trapped water based on the minimum of leftmax and rightmax at each position minus the height of the bar itself. - Time Complexity: ( O(n) ) - Space Complexity: ( O(n) )
  • 📄 TrappedWater.java: Refer Question4.

📂 18_Basic_Sorting_Algorithm
  • 📄**BubbleSort.java**: This file implements the Bubble Sort algorithm to sort an integer array in ascending order by repeatedly swapping adjacent elements if they are in the wrong order.

    • BubbleSort: Sorts the array using nested loops to compare adjacent elements and swap them if necessary until the array is sorted.
      • Time Complexity: ( O(n<sup>2</sup>) ) (worst and average case)
      • Space Complexity: ( O(1) )
  • 📄 CountingSort.java: This program implements the Counting Sort algorithm, which sorts an array of integers by counting the occurrences of each element and using this information to place elements in sorted order.

    • CountingSort: Sorts the array by first counting occurrences of each element, then placing elements back into the array in order based on the counts.
      • Time Complexity: ( O(n + k) ), where ( k ) is the range of the input (if ( k ) is not significantly larger than ( n ))
      • Space Complexity: ( O(n + k) )
  • 📄 InsertionSort.java: This program demonstrates the Insertion Sort algorithm, which iteratively builds a sorted portion of the array by inserting each element into its correct position relative to the already sorted elements.

    • InsertionSort: Sorts the array by iteratively placing each element in its correct position among the already sorted elements to its left.
      • Time Complexity: ( O(n<sup>2</sup>) ) (worst and average case)
      • Space Complexity: ( O(1) )
  • 📄 SelectionSort.java: This program demonstrates the Selection Sort algorithm, which repeatedly selects the smallest (or largest) element from the unsorted portion of the array and swaps it with the first unsorted element.

    • SelectionSort: Sorts the array by finding the minimum element from the unsorted portion and swapping it with the first unsorted element.
      • Time Complexity: ( O(n<sup>2</sup>) ) (worst and average case)
      • Space Complexity: ( O(1) )
  • 📄 Quesiton.java: It contains all the above sorting algorithm to sort an Array in Descending Order.

📂 19_2D_Array
  • 📄 DiagonalSum.java: This program calculates the sum of diagonal elements in a square matrix (matrix).
    • DSum: Computes the sum of elements in both primary and secondary diagonals of the matrix by iterating through each element and checking conditions based on their indices. - Time Complexity: ( O(n) ), where ( n ) is the number of rows or columns in the matrix. - Space Complexity: ( O(1) ).
    • OptimisedDsum: Optimized approach to compute the sum of diagonal elements using a single loop, adding both primary diagonal elements directly and secondary diagonal elements conditionally. -Time Complexity: ( O(n) ), where ( n ) is the number of rows or columns in the matrix. - Space Complexity: ( O(1) ).
  • 📄 Question.java: This file contains methods to perform operations on 2D arrays:
    • Count: Counts the occurrences of a specified integer key in a 2D integer array arr. -Time Complexity: ( O(m \times n) ), where ( m ) is the number of rows and ( n ) is the number of columns in arr. - Space Complexity: ( O(1) ).
    • sum: Computes the sum of elements in the second row of a 2D integer array mat. - Time Complexity: ( O(n) ), where ( n ) is the number of columns in the second row of mat. - Space Complexity: ( O(1) ).
  • 📄 SearchinSortedMatrix.java: This program provides methods to search for a target value (key) in a sorted 2D matrix (matrix):
    • binaryMatrixSearch: Performs binary search on each row of the matrix to find the key. Returns the index if found, otherwise returns "Key not found".
      • Time Complexity: ( O(n \log m) ), where ( n ) is the number of rows and ( m ) is the number of columns in the matrix, assuming all rows have the same length.
      • Space Complexity: ( O(1) ).
    • Optimisedsearch: Efficiently searches for key in the matrix by starting from the top-right corner and adjusting the row or column based on comparisons with key. Returns the index if found, otherwise returns "Key not found".
      • Time Complexity: ( O(n + m) ), where ( n ) is the number of rows and ( m ) is the number of columns in the matrix.
      • Space Complexity: ( O(1) ).
  • 📄 SpiralMatrix.java: This program prints the elements of a 2D matrix (mat) in spiral order, starting from the top-left corner and moving clockwise.
    • printSpiral: Iterates over the matrix in layers, printing elements from top to right, right to bottom, bottom to left, and left to top until all elements are printed.
      • Time Complexity: ( O(m \times n) ), where ( m ) is the number of rows and ( n ) is the number of columns in the matrix.
      • Space Complexity: ( O(1) ).
  • 📄 TransposeMatrix.java: This program computes the transpose of a matrix (matrix), swapping rows with columns.
  • 📄 TwoDArray.java: This program demonstrates the creation, initialization, printing, and searching operations on a 2D integer array (matrix).
    • main: Creates a 3x3 matrix, initializes it with random integers between 0 and 9, prints the matrix, and searches for a specific key value within the matrix. If found, it prints the key and its position; otherwise, it prints -1.
      • Time Complexity: ( O(m * n) ), where ( m ) is the number of rows and ( n ) is the number of columns in the matrix.
      • Space Complexity: ( O(1) ) additional space for variables.
📂 20_Strings
  • 📄 LearnStringBuilder.java: This program demonstrates the use of StringBuilder for various string manipulations.

    • capitalise: Capitalizes the first letter of each word in the given string.
      • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
      • Space Complexity: ( O(n) ).
    • capitalise1: An alternative implementation to capitalize the first letter of each word in the given string using a boolean flag.
      • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
      • Space Complexity: ( O(n) ).
    • main: Demonstrates the use of StringBuilder to build a string of lowercase alphabets and uses capitalise and capitalise1 methods to capitalize words in example strings.
  • 📄 LearnStrings.java: This program demonstrates various string operations in Java.

    • main: Showcases different string operations:
      • Conversion to Upper Case: Converts a string to upper case using toUpperCase.
        • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
        • Space Complexity: ( O(n) ).
      • Conversion to Lower Case: Converts a string to lower case using toLowerCase.
        • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
        • Space Complexity: ( O(n) ).
      • Equality Check: Compares two strings for equality using equals and equalsIgnoreCase.
        • Time Complexity: ( O(n) ), where ( n ) is the length of the shorter string.
        • Space Complexity: ( O(1) ).
      • Concatenation: Concatenates two strings using the + operator.
        • Time Complexity: ( O(n) ), where ( n ) is the length of the concatenated string.
        • Space Complexity: ( O(n) ).
      • Lexicographical Comparison: Compares two strings lexicographically using compareTo.
        • Time Complexity: ( O(n) ), where ( n ) is the length of the shorter string.
        • Space Complexity: ( O(1) ).
  • 📄 PalindromeCheck.java: This program contains methods to check if a given string is a palindrome.

    • isPalindrome: Brute force approach that reverses the string and compares it with the original.
      • Time Complexity: ( O(n^2) ) due to string concatenation in each iteration.
      • Space Complexity: ( O(n) ), where ( n ) is the length of the string.
    • isPalindrome1: Uses the two-pointer technique to compare characters from the start and end of the string.
      • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
      • Space Complexity: ( O(1) ).
    • isPalindrome2: Recursive approach to check for palindrome.
      • Time Complexity: ( O(n) ), where ( n ) is the length of the string.
      • Space Complexity: ( O(n) ) due to the call stack.
    • main: Demonstrates all three palindrome-checking methods with sample strings.
📂 Ongoing Work

torrynn

Releases

No releases published

Packages

No packages published

Languages