Welcome to the Java Repository, your comprehensive guide to learning Java programming! 📚✨
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
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.
- Clone this repository to your local machine.
- Navigate to the directory where you cloned the repository.
- Open any Java file using a text editor or an IDE.
- Compile and run the program using your preferred Java compiler or IDE.
📂 10_Variable_and_DateType
- 📄
Question1.java
: This program takes three numbers (A, B, and C) as input and calculates theiraverage
. It then outputs the calculated average to the console. - 📄
Question2.java
: This program calculates thearea of a square
given the length of its side. - 📄
Question3.java
: This program calculates the final price of items (pencil
,pen
, anderaser
) including an18% 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 ispositive 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 aswitch
statement. - 📄
Question5.java
: This program checks if a given year (var2
) is a leap year using nestedif
statements.
📂 12_Loops
- 📄
Question1.java
: This program reads a number (num
) from the user and calculates the sum of even and odd integers up tonum
. - 📄
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
- Pattern1:
-
📄
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:
-
📄
Pattern1.java
: This Java program generates and prints multiple patterns based on user inputn
:- 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
- Pattern1 (Ascending *):
📂 13_Methods
- 📄
Question1.java
: This Java program defines a methodavg(int a, int b, int c)
that calculates the average of three integersa
,b
, andc
. 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 methodisEven(int a)
that checks if a given integera
is even. The method returnstrue
if the number is even andfalse
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 methodsisPalindrome
to check if a given number or string is a palindrome.boolean isPalindrome(int num)
: Checks if the integernum
is a palindrome by reversing its digits and comparing it to the original number.boolean isPalindrome(String str)
: Checks if the stringstr
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 methodoperation
that performs several mathematical operations on two integersa
andb
.void operation(int a, int b)
: This method prints the minimum (Math.min
), maximum (Math.max
), square root (Math.sqrt
) ofb
,b
raised to the power ofa
(Math.pow
), and the absolute value of-5.242
(Math.abs
).- The
main
method demonstrates the usage ofoperation
with values3
and2
, showcasing these mathematical operations.
- 📄
Question5.java
: This Java program defines a methodsum
that calculates the sum of the digits of an integernum
.int sum(int num)
: This method iteratively calculates the sum of the digits ofnum
using a while loop and returns the computed sum.- The
main
method demonstrates the usage ofsum
with the integer811
, printing the sum of its digits.
📂 16_ARRAYS (Part1)
-
📄
BinarySearch.java
: This Java program implements thebinary search
algorithm to find a target element in a sortedarray
. -
📄
Largestnum.java
: This Java program finds thelargest number
in anarray
ofintegers
. -
📄
LinearSearch.java
: This Java program implements thelinear search
algorithm to find a target element in anarray
. -
📄
PairsArray.java
: This Java program defines a methodPairArray
that takes anarray
ofintegers
as input and prints all possiblepairs
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 themain
method, an examplearray
{ 1, 2, 3, 4 }
is used to demonstrate the functionality ofPairArray
. -
📄
PrintSubArray.java
: This Java program defines a methodSubArray
that prints all possible subarrays of anarray
ofintegers
. 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 indexi
, it iterates over all possible ending indicesj
and prints the elements of the subarray fromi
toj
. 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 themain
method, an example array{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
is used to demonstrate the functionality of theSubArray
method. -
📄
Reverse.java
: This Java program demonstrates two methods to reverse an array of integers.-
rev
method:- This method iterates through the input array
arr
and creates a new arrayrev
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 arrayrev
.
- This method iterates through the input array
-
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 andlast
at the end of the array, and swaps elements untilfirst
surpasseslast
. -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 bothrev
andbetterrev
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 withbuyPrice
. -
📄
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. Returnstrue
if duplicates are found, otherwisefalse
.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 returnstrue
. Otherwise, adds the element to the HashSet and continues. Returnsfalse
if no duplicates are found.Time Complexity
: ( O(n) )Space Complexity
: ( O(n) )
-
📄
Question3.java
: This file defines a methodprice
to calculate the maximum profit that can be achieved from buying and selling stocks based on an integer arrayprice[]
representing daily stock prices.price
: Iterates through theprice
array to calculate the maximum profit by determining the difference between each day's price and the minimum price observed so far (stockprice
). Updatesstockprice
andmaxProfit
accordingly. -Time Complexity
: ( O(n) ) -Space Complexity
: ( O(1) )
-
📄
Question4.java
: Placeholder description. -
📄
Question4.java
: This file contains a methodtrap
that calculates the amount of water trapped between bars in an elevation map represented by an integer arrayarr[]
.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 ofleftmax
andrightmax
at each position minus the height of the bar itself. -Time Complexity
: ( O(n) ) -Space Complexity
: ( O(n) )
-
📄
TrappedWater.java
: ReferQuestion4
.
📂 18_Basic_Sorting_Algorithm
-
📄**
BubbleSort.java
**: This file implements theBubble 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 theCounting 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 theInsertion 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 theSelection 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 integerkey
in a 2D integer arrayarr
. -Time Complexity
: ( O(m \times n) ), where ( m ) is the number of rows and ( n ) is the number of columns inarr
. -Space Complexity
: ( O(1) ).sum
: Computes the sum of elements in the second row of a 2D integer arraymat
. -Time Complexity
: ( O(n) ), where ( n ) is the number of columns in the second row ofmat
. -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 thekey
. 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 forkey
in the matrix by starting from the top-right corner and adjusting the row or column based on comparisons withkey
. 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 specifickey
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 ofStringBuilder
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 ofStringBuilder
to build a string of lowercase alphabets and usescapitalise
andcapitalise1
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
andequalsIgnoreCase
.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) ).
- Conversion to Upper Case: Converts a string to upper case using
-
📄
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.