[go: up one dir, main page]

0% found this document useful (0 votes)
15 views121 pages

Java Program Notes

Uploaded by

pallabakash2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views121 pages

Java Program Notes

Uploaded by

pallabakash2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

SUBJECT: JAVA Programming

Ravikumar Shankar Kumbar


EMAIL : ravikumar@pentagonspace.in
INDEX

Sl.No Chapter pages


1 Introduction to Operators in Java

2 Patterns

3 Number

4 Strings

5 Arrays

6 Bitwise

7 Recursion

❖ Introduction to Operators in Java

➢ Arithmetic Operators
➢ Assignment Operators
➢ Relational (Comparison) Operators
➢ Logical Operators
➢ Unary Operators
➢ Ternary Operator
➢ Special Operators (instance of, etc.)
➢ Bitwise Operators
➢ Control Statements
❖ Patterns Programs
• Square Patterns
➢ Star Pattern
➢ Number Pattern
➢ Alphabet Pattern
➢ Binary Number Pattern
• Floyd Triangle Patterns
➢ Star Pattern
➢ Number Pattern
➢ Alphabet Pattern
➢ Binary Number Pattern
• Inverted Half Pyramid Patterns
➢ Star Pattern
➢ Number Pattern
➢ Alphabet Pattern
➢ Binary Number Pattern
• Pyramid Patterns
➢ Star Pattern
➢ Number Pattern
➢ Alphabet Pattern
➢ Binary Number Pattern
• Inverted Pyramid Patterns
➢ Star Pattern
➢ Number Pattern
➢ Alphabet Pattern
➢ Binary Number Pattern
• Random Patterns
➢ Checkerboard Pattern
➢ Diamond Shape Pattern
➢ Hollow Square and Hollow Pyramid Patterns
➢ Spiral Number Patterns
➢ Zigzag Patterns
❖ Number Programs
I. Basic Number Operations
➢ Print Numbers Between Two Given Numbers
➢ Sum of Numbers Between Two Values
➢ Check Even or Odd Numbers
➢ Print Even Number Between Two Values
➢ Print Odd Number Between Two Values
➢ Swap Two Numbers
➢ Find Factors of a Number
➢ Check If a Number Is Prime
➢ Generating Prime Numbers
➢ Find Factorials of Numbers
➢ Power of a Number
➢ Finding GCD (Greatest Common Divisor)/ HCF (Highest Common Factor)
➢ Finding LCM (Least Common Multiple)
➢ Generate Fibonacci Series Up to n Terms
II. Mathematical Number Problems
➢ Sum of Digits
➢ Product of Digits
➢ Reverse a Number
➢ Checking for Palindromes
➢ Armstrong Numbers
➢ Disarium Number
➢ Strong Number / Special Number / Krishnamurthy Number
➢ Spy Number
➢ Harshad Number
➢ Happy Number
➢ Magic Number
➢ Duck Number
➢ Perfect Numbers
➢ Abundant Numbers
➢ Pronic Number
➢ Amicable Numbers
➢ Automorphic Number
➢ Buzz Number
➢ Unique Number
➢ Ugly Number
III. Advanced and Rare Number Problems
➢ Arithmetic Progression (AP)
➢ Geometric Progression (GP)
➢ Challenge Questions
❖ String Programs

➢ Reversing a String
➢ Checking for Palindromes
➢ Converting Cases (Uppercase/Lowercase/ toggle Case)
➢ Removing Duplicates
➢ Character Frequency Count
➢ Find Count Frequency of Number
➢ Count Vowels and Consonants
➢ Find and Print Unique Elements
➢ Find and Print Duplicate Elements
➢ Anagram Checking
➢ Pangram checking
➢ Find the length of a string without using a function
➢ Find Longest Word in a String
➢ Reverse Words in a Sentence
➢ Check if a String Contains Only Digits
➢ Challenge Questions
❖ Arrays Programs

➢ Print all elements in an array


➢ Print array elements in reverse order
➢ Find Maximum Element
➢ Find the minimum element
➢ Find Second Largest Element
➢ Find Second Smallest Element
➢ Find Count Frequency of Number
➢ Find Count Even Odd
➢ Find and Print Unique Elements
➢ Find and Print Duplicate Elements
➢ Bubble Sort
➢ Selection Sort
➢ Insertion Sort
➢ Quick Sort
➢ Linear Search
➢ Binary Search
➢ calculate All Subarray Sums(array)
➢ Find the subarray with the maximum sum (Kidane’s Algorithm)
➢ Challenge Questions
Chapter -1
Introduction to Operators in Java

Type Operators
Arithmetic +, -, *, /, %
Relational ==, !=, >, <, >=, <=
Logical &&, ||, !
Bitwise &,|
Assignment =, +=, -=, *=, /=, %=
Unary +, -, ++, --
Ternary condition ? true_value : false_value
Special instanceof, Type Casting
I. Arithmetic Operators:
Arithmetic operators in Java are used to perform mathematical operations
such as addition, subtraction, multiplication, division, and modulus (remainder).
These operators work on numeric data types such as int, float, double, and long.
Java Arithmetic Operators
➢ Addition (+)
➢ Subtraction (-)
➢ Multiplication (*)
➢ Division (/)
➢ Modulus (%).
Program: Java code
public class ArithmeticDemo {
public static void main(String[] args) {
// Declaration of two integers, a and b
int a = 10, b = 3;
// Addition: Adds two operands
System.out.println("Addition: " + (a + b)); // 10 + 3 = 13
// Subtraction: Subtracts the second operand from the first
System.out.println("Subtraction: " + (a - b)); // 10 - 3 = 7
// Multiplication: Multiplies two operands
System.out.println("Multiplication: " + (a * b)); // 10 * 3 = 30
// Division: Divides the first operand by the second
System.out.println("Division: " + (a / b)); // 10 / 3 = 3 (integer division)
// Modulus: Finds the remainder when dividing the first operand by the second
System.out.println("Modulus: " + (a % b)); // 10 % 3 = 1 (remainder of 10 divided by3)
}
}
Explanation of Each Operator
Addition (+):
The + operator adds two operands.
Example: 10 + 3 = 13
Output: Addition: 13

Subtraction (-):
The - operator subtracts the second operand from the first operand.
Example: 10 - 3 = 7
Output: Subtraction: 7

Multiplication (*):
The * operator multiplies two operands.
Example: 10 * 3 = 30
Output: Multiplication: 30

Division (/):
The / operator divides the first operand by the second operand.
Example: 10 / 3 = 3 (integer division truncates the decimal part)
Output: Division: 3
Note: If both operands are integers, the result will be an integer. If you want a
floating-point
result, at least one of the operands must be a float or double.

Modulus (%):
The % operator returns the remainder when the first operand is divided by
the second.
Example: 10 % 3 = 1 (the remainder when 10 is divided by 3)
II. Assignment Operators:
Assignment operators are used to assign values to variables. They allow you to
assign a value to a variable and perform operations on that value simultaneously.
These operators are an essential part of programming as they help in modifying or
updating the values stored in variables.
Java Assignment Operators
• Simple Assignment (=)
• Addition Assignment (+=)
• Subtraction Assignment (-=)
• Multiplication Assignment (*=)
• Division Assignment (/=)
• Modulus Assignment (%=)
Java Program: Assignment Operations:
public class AssignmentDemo {
public static void main(String[] args) {
// Declare an integer variable x and assign it the value 10
int x = 10;
// Simple Assignment: Assign value to a variable
x = 20;
System.out.println("Simple Assignment: x = " + x); // 20
// Addition Assignment: Add and assign the result to x
x += 5; // Equivalent to x = x + 5
System.out.println("Addition Assignment: x += 5 -> x = " + x); // 25
// Subtraction Assignment: Subtract and assign the result to x
x -= 3; // Equivalent to x = x - 3
System.out.println("Subtraction Assignment: x -= 3 -> x = " + x); // 22
// Multiplication Assignment: Multiply and assign the result to x
x *= 2; // Equivalent to x = x * 2
System.out.println("Multiplication Assignment: x *= 2 -> x = " + x); // 44
// Division Assignment: Divide and assign the result to x
x /= 4; // Equivalent to x = x / 4
System.out.println("Division Assignment: x /= 4 -> x = " + x); // 11
// Modulus Assignment: Find the remainder and assign the result to x
x %= 5; // Equivalent to x = x % 5
System.out.println("Modulus Assignment: x %= 5 -> x = " + x); // 1
}
}
Explanation of Each Assignment Operator
1. Simple Assignment (=):
o The = operator is used to assign a value to a variable.
o Example: x = 20 assigns the value 20 to the variable x.
o Output: Simple Assignment: x = 20

2. Addition Assignment (+=):


o The += operator adds the right operand to the left operand and assigns the result
to the left operand.
o Example: x += 5 is equivalent to x = x + 5.
o Output: Addition Assignment: x += 5 -> x = 25

3. Subtraction Assignment (=):


o The -= operator subtracts the right operand from the left operand and assigns the
result tothe left operand.
o Example: x -= 3 is equivalent to x = x - 3.
o Output: Subtraction Assignment: x -= 3 -> x = 22
4. Multiplication Assignment (*=):
o The *= operator multiplies the left operand by the right operand and assigns the
result to the left operand.
o Example: x *= 2 is equivalent to x = x * 2.
o Output: Multiplication Assignment: x *= 2 -> x = 44

5. Division Assignment (/=):


o The /= operator divides the left operand by the right operand and assigns the
result to the left operand.
o Example: x /= 4 is equivalent to x = x / 4.
o Output: Division Assignment: x /= 4 -> x = 11

6. Modulus Assignment (%=):


o The %= operator takes the modulus (remainder) of the left operand divided by the
right operand and assigns the result to the left operand.
o Example: x %= 5 is equivalent to x = x % 5.
o Output: Modulus Assignment: x %= 5 -> x = 1
Relational (Comparison):

Relational or comparison operators are used to compare two values or variables.


Theye valuate the relationship between the operands and return a boolean value:
either true or false. These operators are commonly used in conditional statements
like if, while, and for.

Java Relational Operators

• Equal to (==)

• Not equal to (! =)

• Greater than (>)

• Less than (<)

• Greater than or equal to (>=)

• Less than or equal to (<=)


Java Program: Relational Operations:
public class RelationalDemo {
public static void main(String[] args) {
// Declaration of two integers, x and y
int x = 10, y = 5;
// Equal to: Checks if two values are equal
System.out.println("x == y: " + (x == y)); // false
// Not equal to: Checks if two values are not equal
System.out.println("x != y: " + (x != y)); // true
// Greater than: Checks if the first value is greater than the second
System.out.println("x > y: " + (x > y)); // true
// Less than: Checks if the first value is less than the second
System.out.println("x < y: " + (x < y)); // false
// Greater than or equal to: Checks if the first value is greater than or equal to the second
System.out.println("x >= y: " + (x >= y)); // true
// Less than or equal to: Checks if the first value is less than or equal to the second
System.out.println("x <= y: " + (x <= y)); // false
}
Explanation of Each Relational Operator
Equal to (==):
The == operator checks if two values or expressions are equal.
Returns true if the values are the same, otherwise returns false.
Example: x == y checks if 10 == 5. Output: x == y: false
Not equal to (!=):
The != operator checks if two values or expressions are not equal.
Returns true if the values are different, otherwise returns false.
Example: x != y checks if 10 != 5.
Output: x != y: true
Greater than (>):
The > operator checks if the first operand is greater than the second.
Returns true if the first value is greater, otherwise returns false.
Example: x > y checks if 10 > 5.
Output: x > y: true
Less than (<):
The < operator checks if the first operand is less than the second.
Returns true if the first value is less, otherwise returns false.
Example: x < y checks if 10 < 5.
Output: x < y: false
Greater than or equal to (>=):
The >= operator checks if the first operand is greater than or equal to the second.
Returns true if the first value is greater or equal, otherwise returns false.
Example: x >= y checks if 10 >= 5.
Output: x >= y: true
Less than or equal to (<=):
The <= operator checks if the first operand is less than or equal to the second.
Returns true if the first value is less or equal, otherwise returns false.
Example: x <= y checks if 10 <= 5.
Output: x <= y: false.
Logical Operators:
Logical operators are used to perform logical operations, typically on
boolean values. They are essential in decision-making and control flow,
as they help combine multiple conditions in if, while, and other control
statements. These operators return a boolean value (true or false).

Java Logical Operators

▪ Logical AND (&&)

▪ Logical OR (||)

▪ Logical NOT (!)

Java Program: Logical Operations

public class LogicalDemo {

public static void main(String[] args) {

// Declare two boolean variables

boolean a = true, b = false;

// Logical AND: Returns true if both conditions are true

System.out.println("a && b: " + (a && b)); // false (since b is false)

// Logical OR: Returns true if at least one condition is true

System.out.println("a || b: " + (a || b)); // true (since a is true)

// Logical NOT: Reverses the boolean value

System.out.println("!a: " + (!a)); // false (since a is true)

System.out.println("!b: " + (!b)); // true (since b is false)

}
Explanation of Each Logical Operator
Logical AND (&&):
The && operator checks if both conditions are true. It returns true only if
both conditions are true; otherwise, it returns false.
Example: a && b checks if both a and b are true.
Output: a && b: false (since b is false)

Logical OR (||):
The || operator checks if at least one condition is true. It returns true if either
of the conditions is true, and false only if both are false.
Example: a || b checks if either a or b is true.
Output: a || b: true (since a is true)

Logical NOT (!):


The ! operator reverses the logical value of the condition. If the condition is
true, it returns false, and if the condition is false, it returns true.
Example: !a reverses the value of a. If a is true, !a will be false.
Output: !a: false (since a is true).
Short-circuiting behavior:
public class ShortCircuitExample {
public static void main(String[] args) {
int x = 5;
System.out.println((x > 10) && (x < 20)); // false, second condition is
not evaluated
System.out.println((x < 10) || (x > 20)); // true, second condition is not
evaluated
}
}
Unary Operators:
Unary operators are operators that operate on a single operand (i variable or
constant) and perform various operations like incrementing, decrementing,
negating, or inverting a value.
These operators are essential for performing simple operations on variables.
Java Unary Operators
• Unary Plus (+)
• Unary Minus (-)
• Increment (++)
• Decrement (--)
• Logical NOT (!)
Java Program: Unary Operations
public class UnaryDemo {
public static void main(String[] args) {
// Declare an integer variable x
int x = 5;
// Unary Plus: Does nothing but indicates positive value
System.out.println("+x: " + (+x)); // Output: 5 (Unary plus doesn't change the value)
// Unary Minus: Negates the value of the operand
System.out.println("-x: " + (-x)); // Output: -5 (Unary minus changes the sign)
// Increment: Increases the value of the operand by 1
x++; // x = x + 1
System.out.println("x++: " + x); // Output: 6 (x is incremented after the print
statement)
// Decrement: Decreases the value of the operand by 1
x--; // x = x - 1
System.out.println("x--: " + x); // Output: 5 (x is decremented after the print
statement)
// Logical NOT: Reverses the boolean value
boolean flag = true;
System.out.println("!flag: " + (!flag)); // Output: false (logical NOT reverses the
boolean value)
}
}
Explanation of Each Unary Operator
Unary Plus (+): The unary plus operator does nothing to the value—it simply
indicates that the value is positive.
It is mostly used in contexts where the sign of the number must be made explicit,
but in practice, it doesn’t change the value.
Example: +x where x is 5, results in 5.
Output: +x: 5

Unary Minus (-):


The unary minus operator negates the value of its operand. If the operand is
positive, it changes
it to negative, and if the operand is negative, it changes it to positive.
Example: -x where x is 5, results in -5.
Example: -(-5) results in 5.
Output: -x: -5

Increment (++):
The increment operator (++) increases the value of a variable by 1. It can be
used in two forms:
Postfix increment (x++): Increments the value after the expression is evaluated.
Prefix increment (++x): Increments the value before the expression is evaluated.
Example (Postfix): x++ will first return the current value of x, and then
increment x by 1.
Example (Prefix): ++x will increment x by 1 first, and then return the new value.

Output (Postfix)

System.out.println("x++: " + x); // x is 5, so output is 5, and then x becomes 6

Output (Prefix):

System.out.println("--x: " + (--x)); // x becomes 5 before printing, so output is 5


Ternary Operator:

The ternary operator is a shorthand for an if-else statement. It allows you to


write a simple conditional expression in a more compact and readable form.
It is called ternary because it takes three operands.
• The syntax of the ternary operator:
condition? expression1: expression2;
condition: The condition that is evaluated as either true or false.
expression1: This expression is executed if the condition is true.
expression2: This expression is executed if the condition is false.

Key Points

• The ternary operator is used to simplify simple if-else statements.


• It’s a single-line expression
• It returns a value, making it useful in assignments, method calls, etc

Java Program: Ternary Operator Example


public class TernaryDemo {
public static void main(String[] args) {
int x = 10, y = 5;
// Using ternary operator to compare x and y
String result = (x > y) ? "x is greater than y" : "x is not greater than y";
System.out.println(result); // Output: x is greater than y
// Another example with boolean expressions
int max = (x > y) ? x : y;
System.out.println("Max value: " + max); // Output: Max value: 10
}
}
Explanation of the Ternary Operator

Example: String result = (x > y) ? "x is greater than y" : "x is not greater than y";

In this example, if x is greater than y, the string "x is greater than y" will be assigned to
result. Otherwise, "x is not greater than y" will be assigned.

Example of nested ternary operators:

int x = 10, y = 20, z = 30;


int result = (x > y) ? (x > z ? x : z) : (y > z ? y : z);
Control Statements

Control statements in Java determine the flow of execution in a program. They


enable decision-making, looping, and branching to handle different situations effectively

Types of Control Statements

1. Decision-Making Statements

o if statement

o if-else statement

o if-else-if ladder

o switch statement

2. Looping Statements

o for loop

o while loop

o do-while loop

o Enhanced for loop (for-each loop)

3. Jumping Statements

o break

o continue

o return
1. Decision-Making Statements:

1.1 if Statement:
Executes a block of code if the condition evaluates to true.
Syntax:
if (condition) {
// Code to execute if condition is true
}

Example:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}

1.2 if-else Statement:


Executes a block of code if the condition evaluates to true.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int number = 10;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}

1.3 if-else-if Ladder:


Allows checking multiple conditions.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if all conditions are false
}
Example:
int marks = 75;
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 75) {
System.out.println("Grade: A");
} else if (marks >= 50) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: F");
}

1.4 switch Statement


Used to execute one code block among multiple options.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// ...
default:
// Code if no case matches
}

Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
2. Looping Statements
2.1 for Loop:
Executes a block of code a specific number of times.

Syntax:
for (initialization; condition; update) {
// Code to execute
}

Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}

2.2 while Loop


Executes a block of code as long as the condition is true.
Syntax:
while (condition) {
// Code to execute
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}

2.3 do-while Loop


Executes a block of code at least once, then repeats while the condition is true.
Syntax:
do {
// Code to execute
} while (condition);
Example:
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
2.4 Enhanced for Loop (For-Each Loop)

Syntax:
for (type variable : array/collection) {
// Code to execute
}
Example:
int[] numbers = {10, 20, 30};
for (int num : numbers) {
System.out.println(num);
}

3. Jumping Statements

3.1 break Statement:


Used to exit a loop or switch statement prematurely.

Example (In Loop):

for (int i = 1; i <= 5; i++) {


if (i == 3) {
break;
}
System.out.println("Iteration: " + i);
}
// Output: 1, 2

3.2 continue Statement


Skips the current iteration and moves to the next.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Iteration: " + i); // Output: 1, 2, 4, 5
}
3.3 return Statement:
Used to exit from a method and optionally return a value.
Example:
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = sum(5, 10);
System.out.println("Sum: " + result); // Sum: 15
}
Patterns programs

Star Pattern:
CODE PATTERN
public class StarPattern { *****
public static void main(String[] args) {
*****
int n = 5; // Size of the square pattern
*****
System.out.println("Star Pattern:");
*****
for (int i = 1; i <= n; i++) { // Outer loop for rows
*****
for (int j = 1; j <= n; j++) { // Inner loop for columns

System.out.print("* "); // Print star


}

System.out.println(); // Move to next row


}
}
}

Iteration-wise Explanation:

Iteration Outer Loop (Row) Inner Loop Pattern So Far


(Column)
1 I=1 J=1 to 5 *****
2 I=2 J=1 to 5 *****
*****
3 I=3 j = 1 to 5 *****
*****
*****
4 I=4 j = 1 to 5 *****
*****
*****
*****
5 I=5 j = 1 to 5 *****
*****
*****
*****
*****
1.2 Number Pattern

code Pattern
public class NumberPattern {
public static void main(String[] args) { 1 2 3 4 5
int n = 5; 6 7 8 9 10
int num=1; 11 12 13 14 15
System.out.println("Number Pattern:"); 16 17 18 19 20
for (int i = 1; i <= n; i++) { 21 22 23 24 25
for (int j = 1; j <= n; j++) {
System.out.print(num+ " ");
num++;
}
System.out.println();
}
}
}
public class NumberPattern {
public static void main(String[] args) { 12345
int n = 5;
System.out.println("Number Pattern:"); 12345
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) { 12345
System.out.print(i + " ");
} 12345
System.out.println();
} 12345
}
}
public class NumberPattern { 11111
public static void main(String[] args) {
int n = 5; 22222
System.out.println("Number Pattern:");
for (int i = 1; i <= n; i++) { 33333
for (int j = 1; j <= n; j++) {
System.out.print(i + " "); 44444
}
System.out.println(); 55555
}
}
}
1.2 Alphabet Pattern:

code Pattern
public class AlphabetPattern {
public static void main(String[] args) { ABCDE
int n = 5;
char ch = 'A'; FGHIJ
System.out.println("Alphabet Pattern:");
for (int i = 1; i <= n; i++) { KLMNO
for (int j = 1; j <= n; j++) {
System.out.print(ch + " "); PQRST
ch++;
} UVWXY
System.out.println();
}
}
}
public class AlphabetPattern { AAAAA
public static void main(String[] args) {
int n = 5; BBBBB
char ch = 'A';
System.out.println("Alphabet Pattern:"); CCCCC
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) { DDDDD
System.out.print(ch + " ");
} EEEEE
System.out.println();
ch++;
}
}
}
public class AlphabetPattern {
public static void main(String[] args) { ABCDE
int n = 5;
System.out.println("Alphabet Pattern:"); ABCDE
for (int i = 1; i <= n; i++) {
char ch = 'A'; ABCDE
for (int j = 1; j <= n; j++) {
System.out.print(ch + " "); ABCDE
ch++;
} ABCDE
System.out.println();
}
}}
1.2 Binary Number Patterns
CODE PATTERN
public class BinaryPattern {
public static void main(String[] args) {
int n = 5; 01010
int num = 0;
System.out.println("Binary Pattern:"); 10101
for (int i = 1; i <= n; i++) { 01010
for (int j = 1; j <= n; j++) {
System.out.print(num + " "); 10101
num = 1 - num;
} 01010
System.out.println();
}
}
}
public class BinaryPattern {
public static void main(String[] args) {
int n = 5; 00000
System.out.println("Binary Pattern:");
for (int i = 1; i <= n; i++) { 11111
int num = (i % 2 == 0) ? 1 : 0; 00000
for (int j = 1; j <= n; j++) {
System.out.print(num + " "); 11111
}
System.out.println(); 00000
}
}
}
public class BinaryPattern {
11111
public static void main(String[] args) {
int n = 5; 00000
System.out.println("Binary Pattern:");
for (int i = 1; i <= n; i++) { 11111
for (int j = 1; j <= n; j++) { 00000
System.out.print((j % 2) + " ");
} 11111
System.out.println();
}
}
}
2.Floyd Triangle Patterns:

CODE PATTERN
public class FloydTriangle { *
public static void main(String[] args) {
int rows = 5; **
System.out.println("Floyd's Triangle with Stars:"); ***
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) { ****
System.out.print("* ");
} *****
System.out.println();
}
}
}

Iteration-wise Explanation:

Iteration Outer Loop (Row) Inner Loop Pattern So Far


(Column)
1 I=1 J=1 *
2 I=2 J=1 to 2 *
**
3 I=3 j = 1 to 3 *
**
***
4 I=4 j = 1 to 4 *
**
***
****
5 I=5 j = 1 to 5 *
**
***
****
*****
1.Number patterns

code Pattern
public class FloydTrianglePattern { 1
public static void main(String[] args) {
int rows = 5; 23
int num = 1;
System.out.println("Floyd's Triangle with Incrementing 456
Numbers:");
for (int i = 1; i <= rows; i++) { 7 8 9 10
for (int j = 1; j <= i; j++) {
System.out.print(num + " "); 11 12 13 14 15
num++;
}
System.out.println();
}
}
}
public class FloydTrianglePattern { 1
public static void main(String[] args) {
int rows = 5; 22
System.out.println("Floyd's Triangle with Same
Numbers:"); 333
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) { 4444
System.out.print(i + " ");
} 55555
System.out.println();
}
}
}
public class FloydTriangleColumns { 1
public static void main(String[] args) {
int rows = 5; // Number of rows 12
System.out.println("Floyd's Triangle with Same Numbers
in Each Column:"); 123
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) { 1234
System.out.print(j + " "); // Print column number
} 12345
System.out.println();
}
}
}
2. Alphabet Patterns
code Pattern
public class FloydTriangleAlphabets { A
public static void main(String[] args) {
int rows = 5; BC
char ch = 'A';
System.out.println("Floyd's Triangle with Incrementing DEF
Alphabets:");
for (int i = 1; i <= rows; i++) { GHIJ
for (int j = 1; j <= i; j++) {
System.out.print(ch + " "); KLMNO
ch++;
}
System.out.println();
}
}
}
public class FloydTriangleSameRow { A
public static void main(String[] args) {
int rows = 5; BB
System.out.println("Floyd's Triangle with Same Alphabets
in Each Row:"); CCC
for (int i = 1; i <= rows; i++) {
char ch = (char) ('A' + i - 1); DDDD
for (int j = 1; j <= i; j++) {
System.out.print(ch + " "); EEEEE
}
System.out.println();
}
}
}
public class FloydTriangleColumns { A
public static void main(String[] args) {
int rows = 5; AB
System.out.println("Floyd's Triangle with Same Alphabets
in Each Column:"); ABC
for (int i = 1; i <= rows; i++) {
char ch = 'A'; ABCD
for (int j = 1; j <= i; j++) {
System.out.print(ch + " "); ABCDE
ch++;
}
System.out.println();
}
}
}
2. Binary Patterns
code Pattern
public class FloydTriangleBinary { 0
public static void main(String[] args) {
int rows = 5; 10
int num = 0;
for (int i = 1; i <= rows; i++) { 101
for (int j = 1; j <= i; j++) {
System.out.print(num + " "); 0101
num = (num == 0) ? 1 : 0;
} 01010
System.out.println();
}
}
}

public class FloydTriangleColumnsBinary { 0


public static void main(String[] args) {
int rows = 5; 01
for (int i = 1; i <= rows; i++) {
// Column loop 010
for (int j = 1; j <= i; j++) {
System.out.print((j % 2 == 1 ? 0 : 1) + " "); 0101
}
System.out.println(); 01010
}
}
}

public class FloydTriangleSameRowBinary { 1


public static void main(String[] args) {
int rows = 5 00
for (int i = 1; i <= rows; i++) {
int value = i % 2; 111
for (int j = 1; j <= i; j++) {
System.out.print(value + " "); 0000
}
System.out.println(); 11111
}
}
}
3. Inverted Half Pyramid Star Pattern:
CODE PATTERN
public class InvertedHalfPyramidStar { *****

public static void main(String[] args) { ****

int rows = 5; ***


for (int i = 1; i <= rows ; i++) {
**
for (int j = i; j <=rows; j++) {
*
System.out.print("* ");
}
System.out.println();
}
}
}

Iteration-wise Explanation:

Iteration Outer Loop (Row) Inner Loop Pattern So Far


(Column)
1 I=1 j = 1 to 5 *****
2 I=2 J=2 to 5 *****
****
3 I=3 j = 3 to 5 *****
****
***
4 I=4 j = 4 to 5 *****
****
***
**

5 I=5 j = 5 to 5 *****
****
***
**
*
1.Number patterns

code Pattern
public class InvertedHalfPyramidIncrementingNumbers{ 12345
public static void main(String[] args) {
int rows = 5; 6789
char ch='A';
for (int i = 1; i <= rows ; i++) { 10 11 12
for (int j = i; j <=rows; j++) {
System.out.print( ch+" "); 13 14
ch++;
} 15
System.out.println();
}
}
}
public class InvertedHalfPyramidSameNumbers { 11111
public static void main(String[] args) {
int rows = 5; 2222
for (int i = 1; i <= rows ; i++) {
for (int j = i; j <=rows; j++) { 333
System.out.print( i+" ");
} 44
System.out.println();
} 5
}
}
public class InvertedHalfPyramidSameNumbersInColumns{ 12345
public static void main(String[] args) {
int rows = 5; 1234
for (int i = 1; i <= rows ; i++) {
int num=1; 123
for (int j = i; j <=rows; j++) {
System.out.print( num+" "); 12
num++;
} 1
System.out.println();
}
}
}
2. Alphabet patterns

code Pattern
public class InvertedHalfPyramidIncrementingAlphabets{ ABCDE
public static void main(String[] args) {
int rows = 5; FGHI
char ch='A';
for (int i = 1; i <= rows ; i++) { JKL
for (int j = i; j <=rows; j++) {
System.out.print(ch +" "); MN
ch ++;
} O
System.out.println();
}
}
}

public class InvertedHalfPyramidSameAlphabetsInRows { AAAAA


public static void main(String[] args) {
int rows = 5; BBBB
char ch='A';
for (int i = 1; i <= rows ; i++) { CCC
for (int j = i; j <=rows; j++) {
System.out.print(ch +" "); DD
}
ch ++; E
System.out.println();
}
}
}

public class InvertedHalfPyramidSameNumbersInColumns{ ABCDE


public static void main(String[] args) {
int rows = 5; ABCD
for (int i = 1; i <= rows ; i++) {
char ch='A'; ABC
for (int j = i; j <=rows; j++) {
System.out.print(ch +" "); AB
ch ++;
} A
System.out.println();
}
}
}
3. binary patterns
code Pattern
public class InvertedHalfPyramidBinary { 01010
public static void main(String[] args) {
1010
int rows = 5;
010
for (int i = 1; i <= rows ; i++) {
for (int j = i; j <=rows; j++) { 10
System.out.print((j % 2 ) + " ");
0
}
System.out.println();
}
}
}
public class InvertedHalfPyramidColumnsBinary { 01010
public static void main(String[] args) {
int rows = 5; 0101
for (int i = 1; i <= rows ; i++) {
010
for (int j = i; j <=rows; j++) {
System.out.print(((i+j) % 2 ) + " "); 01
}
System.out.println(); 0
}
}
}

public class InvertedHalfPyramidSameRowBinary { 00000


public static void main(String[] args) {
int rows = 5; 1111
for (int i = 1; i <= rows ; i++) {
000
for (int j = i; j <=rows; j++) {
System.out.print((i % 2 == 1 ? 0 : 1) + " "); 11
}
System.out.println(); 0
}
}
}
}
3. Pyramid Star Pattern

CODE PATTERN
public class PyramidStar {
public static void main(String[] args) {
int rows = 5; *
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) { ***
System.out.print(" ");
} *****
for (int k = 1; k <= i; k++) {
System.out.print("*"); *******
}
for (int l = 2; l <= k; l++) { *********
System.out.print("*");
}
System.out.println();
}
}
}

Iteration-wise Explanation:

Iteration Outer Inner Loop (Column) Pattern So Far


Loop
(Row)
1 I=1 Spaces: j = 1 to 5 → " " (4 spaces) * *
Stars: k = 1 to 1 → *
Stars: l= 2 to 1 → (no stars in this loop)
2 I=2 Spaces: j = 2 to 5 → " " (3 spaces) * *
Stars: k = 1 to 2 → ** *** ***
Stars: l= 2 to 2 → *

3 I=3 Spaces: j = 3 to 5 → " " (2 spaces) * *


Stars: k = 1 to 3 → *** *** ***
Stars: l= 2 to 3 → ** *****
4 I=4 Spaces: j = 4 to 5 → " " (1 space) * *
Stars: k = 1 to 4 → **** *** ***
Stars: l = 2 to 4 → *** *****
*******

5 I=5 Spaces: j = 5 to 5 → "" (0 spaces) * *


Stars: j = 1 to 5 → ***** *** ***
Stars: j = 2 to 5 → **** *****
*******
*********
1.Number patterns
code Pattern
public class PyramidIncrementingNumbers{ 1
public static void main(String[] args) {
int rows = 5; 234
int num = 1;
56789
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) { 10 11 12 13 14 15 16
System.out.print(" ");
} 17 18 19 20 21 22 23 24 25
for (int k = 1; k <= i; k++) {
System.out.print(num + " ");
num++;
}
for (int l = 2; l <= i; l++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
}
}
public class PyramidSameNumbers { 1
public static void main(String[] args) {
int rows = 5; 222
for (int i = 1; i <= rows; i++) {
33333
for (int j = i; j <= rows; j++) {
System.out.print(" "); 4444444
}
for (int k = 1; k <= i; k++) { 555555555
System.out.print(i+ " ");
}
for (int l = 2; l <= i; l++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
public class PyramidSameNumbersInColumns{
public static void main(String[] args) {
int rows = 5; 1
for (int i = 1; i <= rows; i++) {
123
int num=1;
for (int j = i; j <= rows; j++) { 12345
System.out.print(" ");
} 1234567
for (int k = 1; k <= i; k++) {
System.out.print(num+ " "); 123456789
num++;
}
for (int l = 2; l <= i; l++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
}
}
public class PyramidSameNumbersInColumns{ 1
public static void main(String[] args) {
int rows = 5; 121
for (int i = 1; i <= rows; i++) {
12321
for (int j = i; j <= rows; j++) {
System.out.print(" "); 1234321
}
for (int k = 1; k <= i; k++) { 123454321
System.out.print(k+ " ");
}
for (int l = i - 1; l >= 1; l--) {
System.out.print(l + " ");
}
System.out.println();
}
}
}
2. Alphabet patterns
code Pattern
public class PyramidIncrementingAlphabets{ A
public static void main(String[] args) {
int rows = 5; BCD
char ch= 'A';
EFGHI
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) { JKLMNOP
System.out.print(" ");
} QRSTUVWXY
for (int k = 1; k <= i; k++) {
System.out.print(ch + " ");
ch++;
}
for (int l = 2; l <= i; l++) {
System.out.print(ch + " ");
ch++;
}
System.out.println();
}
}
}
public class PyramidSameAlphabetsInRows { A
public static void main(String[] args) {
int rows = 5; BBB
char ch= 'A';
CCCCC
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) { DDDDDDD
System.out.print(" ");
} EEEEEEEEE
for (int k = 1; k <= i; k++) {
System.out.print(ch + " ");
}
for (int l = 2; l <= i; l++) {
System.out.print(ch + " ");
}
ch++;
System.out.println();
}
}
}
public class Pyramid{
public static void main(String[] args) { A
int rows = 5;
ABC
for (int i = 1; i <= rows; i++) {
char ch= 'A'; ABCDE
for (int j = i; j <= rows; j++) {
System.out.print(" "); ABCDEFG
}
for (int k = 1; k <= i; k++) { ABCDEFGHI
System.out.print(ch + " ");
ch++;
}
for (int l = 2; l <= i; l++) {
System.out.print(ch + " ");
ch++;
}
System.out.println();
}
}
}
public class PyramidAlphabets { A
public static void main(String[] args) {
int rows = 5; ABA
for (int i = 1; i <= rows; i++) {
ABCBA
for (int j = i; j <= rows; j++) {
System.out.print(" "); ABCDCBA
}
for (int k = 1; k <= i; k++) { ABCDEDCBA
System.out.print((char) ('A' + k - 1) + " ");
}
for (int l = i - 1; l >= 1; l--) {
System.out.print((char) ('A' + l - 1) + " ");
}
System.out.println();
}
}
}
3. Binary Patterns
code Pattern
public class PyramidBinary { 0
public static void main(String[] args) {
int rows = 5; 010
for (int i = 1; i <= rows; i++) {
01010
for (int j = i; j <= rows; j++) {
System.out.print(" "); 0101010
}
for (int k = 1; k <= i; k++) { 010101010
System.out.print((k % 2 == 0 ? 1 : 0) + " ");
}
for (int l = 2; l <= i; l++) {
System.out.print((l % 2 == 0 ? 1 : 0) + " ");
}
System.out.println();
}
}
}
}
public class PyramidBinary { 1
public static void main(String[] args) {
int rows = 5; 101
for (int i = 1; i <= rows; i++) {
10101
for (int j = i; j <= rows; j++) {
System.out.print(" "); 1010101
}
for (int k = 1; k <= i; k++) { 101010101
System.out.print(k % 2 + " ");
}

for (int l = i - 1; l >= 1; l--) {


System.out.print(l % 2 + " ");
}
System.out.println();
}
}
}
public class PyramidBinary {
public static void main(String[] args) { 1
int rows = 5;
000
for (int i = 1; i <= rows; i++) {
for (int j = i; j <= rows; j++) { 11111
System.out.print(" ");
} 0000000
int value = (i % 2 == 0) ? 0 : 1;
111111111
for (int k = 1; k <= i; k++) {
System.out.print(value + " ");
}
for (int l = i - 1; l >= 1; l--) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
Random Patterns
1.Checkerboard Pattern
code Pattern
public class CheckerboardPattern { * * * *
public static void main(String[] args) { * * * *
int rows = 8, cols = 8; * * * *
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
* * * *
if ((i + j) % 2 == 0) * * * *
System.out.print("* "); * * * *
else * * * *
System.out.print(" "); * * * *
}
System.out.println();
}
}
}

2. Diamond Pattern Star


code Pattern
public class DiamondPattern {
public static void main(String[] args) { *
int n=5;
for (int i = 1; i <= n; i++) { ***
for (int j = i; j < n; j++) {
*****
System.out.print(" ");
} *******
for (int k = 1; k <= i; k++) {
System.out.print("*"); *********
}
for (int l = 1; l < i; l++) { *******
System.out.print("*");
} *****
System.out.println();
} ***
for (int i = n - 1; i >= 1; i--) {
*
for (int j = n; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
for (int l = 1; l < i; l++) {
System.out.print("*");
}
System.out.println();} } }}
3.Diamond Pattern Number

code Pattern
int n = 5;
for (int i = 1; i <= n; i++) { 1
for (int j = i; j < n; j++) {
121
System.out.print(" ");
} 12321
for (int k = 1; k <= i; k++) {
System.out.print(k); 1234321
}
int num = i - 1; 123454321
for (int l = 1; l < i; l++) {
1234321
System.out.print(num);
num--; 12321
}
System.out.println(); 121
}
1
for (int i = n - 1; i >= 1; i--) {
for (int j = n; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print(k);
}
int num = i - 1;
for (int l = 1; l < i; l++) {
System.out.print(num);
num--;
}
System.out.println();
}
}
4.Hollow Square

code Pattern
class HollowSquarePattern {
public static void main(String[] args) { *****
int size = 5; * *
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) { * *
if (i == 1 || i == size || j == 1 || j == size)
* *
System.out.print("* ");
else *****
System.out.print(" ");
}
System.out.println();
}
}
}

5.Hollow Pyramid Pattern

code Pattern
public class HollowPyramidPattern {
public static void main(String[] args) { *
int n = 5; **
for (int i = 1; i <= n; i++) {
for (int j = n - i; j > 0; j--) * *
System.out.print(" ");
* *
for (int j = 1; j <= 2 * i - 1; j++) {
if (j == 1 || j == 2 * i - 1 || i == n) *********
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
6.Double Hill Pattern

code Pattern
class DoubleHillPattern {
* *
public static void main(String[] args) { *** ***
int n = 5;
***** *****
for (int i = 1; i <= n; i++) {
******* *******
for (int j = i; j <= n; j++) { ******************
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
for (int j = i; j < n; j++) {
System.out.print(" ");
}
for (int j = i; j < n; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
7. Double Hill Pattern

code Pattern
class DoubleHillPattern {
public static void main(String[] args) { **********
int n = 5; **** ****
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) { *** ***
System.out.print("*");
** **
}
for (int j =0; j <i; j++) { * *
System.out.print(" ");
}
for (int j =0; j <i; j++) {
System.out.print(" ");
}
for (int j = i; j < n; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
class DoubleHillPattern {
public static void main(String[] args) { * *
int n = 5; ** **
for (int i = 0; i < n; i++) {
for (int j =0; j <=i; j++) { *** ***
System.out.print("*");
**** ****
}
for (int j = i+1; j < n; j++) { **********
System.out.print(" ");
}
for (int j = i+1; j < n; j++) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Important pattern Notes
Square pattern
Pattern Code
***** for (int i = 1; i <= 5; i++) {
***** for (int j = 1; j <= 5; j++) {
***** System.out.print("* ");
***** }
***** System.out.println();
}

Triangle Pattern
Normal Code(increment) Inverted Code(decrement)
* for (int i = 1; i <= 5; i++) { * * * * * for (int i = 1; i <= 5; i++) {
** for (int j = 1; j <=i; j++) { * * * * for (int j = i; j <= 5; j++) {
*** System.out.print("*"); *** System.out.print("* ");
**** } ** }
***** System.out.println(); * System.out.println();
} }

Pyramid Pattern Type -1


Normal Code Inverted Code
* for (int i = 1; i <= 5; i++) { * * * * * for (int i = 1; i <= 5; i++) {
** for (int j = i; j < 5; j++) { **** for (int j = 1; j < i; j++) {
*** System.out.print(" "); * * * System.out.print(" ");
**** } ** }
* * * * * for (int j = 1; j <= i; j++) { * for (int j = i; j <= 5; j++) {
System.out.print("*" + " "); System.out.print("* ");
} }
System.out.println(); System.out.println();
} }

Pyramid Pattern Type -2


Normal Code Inverted Code
* for (int i = 1; i <= 5; i++) { ********* for (int i = 1; i <= 5; i++) {
*** for (int j = i; j < 5; j++) { ******* for (int j = 1; j < i; j++) {
***** System.out.print(" "); ***** System.out.print(" ");
******* } *** }
********* int len = 2 * i - 1; * int len = (2 * 5) - (2 * i - 1);
for (int j = 1; j <= len; j++) for (int j = 1; j <= len;
{ j++){
System.out.print("*"); System.out.print("*");
} }
System.out.println(); System.out.println();
} }
Extra pattern Design
Number Manipulations
I. Basic Number Operations
1.Print Numbers Between Two Given Numbers
class printNumbersBetween {
public static void main(String... args) {
int start=0;
int end=10;
System.out.println("Numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
OutPut=Numbers between 0 and 10: 0 1 2 3 4 5 6 7 8 9 10

2.Sum of Numbers Between Two Values


class sumOfNumbersBetween{
public static void main(String... args) {
int start=0;
int end=10;
int sum=0;
for (int i = start; i <= end; i++) {
sum=sum+i;
}
System.out.println("Sum of numbers between " + start + " and " + end + " is: " + sum);
}
}
OutPut=Sum of numbers between 0 and 10 is: 55

3.Check Even or Odd Numbers


Method 1: Check Even or Odd using Modulus Operator
class CheckEvenOrOdd {
public static void main(String... args) {
int num=25;
if(num%2==0){
System.out.println("number is even");
}else{
System.out.println("number is odd");
}
}
} OutPut= number is odd
Method-2: Using Division
if ((num / 2) * 2 == num) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}
Method 3: Using String Array
int num=25;
String[ ] result={"number is Even" , "number is odd "};
System.out.println(result[num%2]);

Method 4: Using Bitwise AND Operator


if ((num2 & 1) == 0) {
System.out.println(num2 + " is even");
} else {
System.out.println(num2 + " is odd");
}
4.Print Even Number Between Two Values
Public class PrintEvenNumber{
public static void main(String... args) {
int start=0;
int end=10;
for (int i = start; i <= end; i++) {
if(i%2==0){
System.out.print(i+",");
}
}
}
}
OutPut= 0,2,4,6,8,10
5.Print Odd Number Between Two Values
Public class PrintOddNumber{
public static void main(String... args) {
int start=0;
int end=10;
for (int i = start; i <= end; i++) {
if(i%2!=0){
System.out.print(i+",");
}
}
}
} Output= 1,3,5,7,9
6.Swap Two Numbers

Method 1: Using a Temporary Variable


public class NumberSwapper {
public static void main(String... args) {
int a = 5, b = 10;
System.out.println("Before Swap: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Output= After Swap: a = 10, b = 5

Method 2: Using Arithmetic Operators (Addition and Subtraction)


a = a + b;
b = a - b;
a = a - b;
System.out.println("After Swap: a = " + a + ", b = " + b);
Output= After Swap: a = 10, b = 5

Method 3: Using Arithmetic Operators (Multiplication and Division)


a = a * b;
b = a / b;
a = a / b;
System.out.println("After Swap: a = " + a + ", b = " + b);}
Output= After Swap: a = 10, b = 5
Method 4: Using Bitwise XOR
int a = 5, b = 10;
System.out.println("Before Swap: a = " + a + ", b = " + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After Swap: a = " + a + ", b = " + b);
Output= After Swap: a = 10, b = 5
7.Find Factors of a Number

public class FactorFinder {


public static void main(String... args) {
int number=18;
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
Output= Factors of 18 are: 1 2 3 6 9 18
8.Check If a Number Is Prime
Definition: A prime number is a number greater than 1 that has
exactly two distinct positive divisors: 1 and itself
Examples: 2, 3, 5, 7, 11, etc

Approach 1: Counting Divisors

Check if the number has exactly two divisors (1 and itself).

public class PrimeCheck {


public static boolean isPrime(int n) {
if (n <= 1) return false; // 0 and 1 are not prime
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
}
return count == 2;
}
public static void main(String[] args) {
int number = 29;
System.out.println("Is " + number + " prime? " + isPrime(number));
}
}
Approach 2: Checking Divisors from 2 to n-1

Check if the number has any divisors other than 1 and itself.
public static boolean isPrime(int n) {
if (n <= 1)
return false;
int count = 0;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
count++;
}
}
return count == 0;
}

Approach-3: Iterating up to n/2

• Any factor of a number greater than n/2 must have a corresponding factor smaller
than n/2.
So, we only need to check up to n/2.
public static boolean isPrime(int n) {
if (n <= 1)
return false;
int count = 0;
for (int i = 2; i < n/2; i++) {
if (n % i == 0) {
count++;
}
}
return count == 0;
}
Approach 4: Iterating Up to the Square Root of n
If n has a factor greater than nn, it must have a corresponding factor smaller than nn.
So, we only need to check up to nn
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
Output=true
9. Generate Prime Numbers in a Range:
public class PrimeRange {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
public static void printPrime(int n) {
for (int i = 0; i <n; i++) {
if (isPrime(i)) {
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
printPrime(10);
}
Output=1,3,5,7

10. Find Factorials of Numbers


• The product of all integers from 1 to n
• Example:5! =5*4*3*2*1=120
Method 1: using Iterative:
public class FactorialIterative {
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " (Iterative):
" + factorial(number));
}
}
Output=120
Method 2: using Recursive:
public class FactorialRecursive {
public static int factorial(int n) {
if (n == 1 || n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " (Recursive):" + factorial(number));
}
}
Output=120

11.Power of a Number:

• The power of a number x^y means multiplying x by itself y times.


• Formula: Power(x,y)=xy x=base , y=exponent
• Power (2,3) =2*2*2=8

Java Code:

public static int power(int base, int exponent) {


int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
12.GCD (Greatest Common Divisor)/ HCF (Highest Common Factor):
The largest positive integer that divides two numbers without leaving a remainder.
Example: For 12 and 18, the divisors are
• 12:1,2,3,4,6,12
• 18:1,2,3,6,9,18
• The largest common divisor is 6.

Method-1: Brute-Force Method:


public static int gcd(int a, int b) {
int gcd = 1;
for (int i = Math.min(a, b); i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
gcd = i;
break;
}
}
return gcd;
}

Output= 6
Method 2: Euclidean Algorithm (Iterative)

public class GCDIterative {


public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
int num1 = 12, num2 = 18;
System.out.println("GCD of " + num1 + " and " + num2 + " (Iterative): " +
findGCD(num1, num2));
}
}
Output= 6
METHOD 3: Subtraction Method
Repeatedly subtract the smaller number from the larger number until both
numbers
are That number is the GCD
public class GCD {
public static int findGCD(int a, int b) {
while (a! = b) {
if(a>b) {
a=a-b;
} else {
b=b-a;
}
}
return a;
}
public static void main(String[] args) {
int num1 = 12, num2 = 18;
System.out.println("GCD of " + num1 + " and " + num2 + " (Iterative): " +
findGCD(num1, num2));
}
}
Output= 6
13. LCM (Least Common Multiple):
• The smallest positive integer that is divisible by both numbers.
• Formula: LCM(a,b)= a×b/ GCD(a,b) Example: For 12 and 18, divisors
• Multiples of 12=1,2,3,4,6,12 Multiples of 18=1,2,3,6,9,18
• The smallest common multiple is 36
Java Code:
public class LCM {
public static int findLCM(int a, int b) {
return (a * b) / findGCD(a, b);
}
public static void main(String[] args) {
int num1 = 12, num2 = 18;
System.out.println("LCM of " + num1 + " and " + num2 + ": " +findLCM(num1,
num2));
}
}
Output=36
Method 2:(without using formula or HCF/GCD)
public class LCM {
public static int findLCM(int a, int b) {
int max=Math.max(a,b);
int lcm=max;
while(true){
if(lcm%a==0 && lcm%b == 0){
return lcm;
}
lcm+=max;
}
}
public static void main(String[] args) {
int num1 = 12, num2 = 18;
System.out.println("LCM of " + num1 + " and " + num2 + ": " +
findLCM(num1, num2));
}
}
Output=36
14. Generate Fibonacci Series Up to n Terms
• Sequence where F(n)=F(n−1)+F(n−2)
• Example: 0,1,12,3,5,8,13,21……etc.
Method 1: using Iterative:
public class FibonacciIterative {
public static void generateFibonacci(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series (Iterative): ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
public static void main(String[] args) {
generateFibonacci(10);
}
}
Output=0,1,1,2,3,5,8,13,21,34
Mathematical Number Problems

Core Logic: Extracting and Removing Digits


The fundamental logic behind solving many number-based problems involves
processing each digit of a number one by one.
We do this using:
• Extracting the last digit: num % 10 (gives the last digit)
• Removing the last digit: num /= 10 (removes the last digit)

Base Template:
Most problems use this fundamental logic:

int num = 1234;


while (num > 0) {
int lastDigit = num % 10; Extract the last digit

Based on the problem,


insert your logic here

num /= 10; Remove the last digit from the number


}

Example: Cou nting Digits in a Number

int num=1234;
int count=0;
while (num > 0) {
int lastDigit = num % 10;
count++;
num /= 10;
}
System.out.println("Number of digits: " + count);

This approach is applicable to:


Sum of Digits
Product of Digits
Reverse a Number
Checking for Palindromes
Armstrong, Disarium, Strong, Happy, Spy, Harshad, Ugly Numbers
15. Sum of Digits:
The sum of digits means adding all the individual digits of a number.
• Number:123
• Sum=1+2+3
• Java Code:

public static int sumOfDigits(int num) {


int sum = 0;
while (num > 0) {
int lastDigit = num % 10;
sum+=lastDigit
num /= 10;
}
return sum;
}
Output=6

16. Product of Digits

• The product of digits means multiplying all the individual digits of a number
• Number=123
• Product=1*2*3=6
• Java Code:
public static int productOfDigits(int num) {
int product = 1;
product *= num % 10;
while (num > 0) {
int lastDigit = num % 10;
product *=lastDigit
num /= 10;
}
return product;
}
Output=6
17.Reverse a Number
• Reverse the digits by repeatedly taking the last digit
Java code:
public class ReverseNumber {
public static int reverse(int num) {
int reverse = 0;
while (num > 0) {
int lastDigit= num % 10;
reverse = reverse * 10 + lastDigit;
num /= 10;
}
return reverse;
}
public static void main(String[] args) {
int number = 1234;
System.out.println("Reversed number: " + reverse(number));
}
} Output=4321

18. Check If a Number Is a Palindrome:


• A number is a palindrome if reversing its digits yields the same number.
Steps:1. Reverse the number.
2.Compare the reversed number with the original.
Java code:
public class PalindromeNumber {
public static boolean isPalindrome(int num) {
int original = num, reverse = 0;
while (num > 0) {
int lastDigit= num % 10;
reverse = reverse * 10 + lastDigit;
num /= 10;
}
return reverse == original;
}
public static void main(String[] args) {
int number = 121;
System.out.println(number + " is a palindrome? " + isPalindrome(number));
}
}
Output=121
19. Check If a Number Is Armstrong
• An Armstrong number equals the sum of its digits raised to the power of
the number of digits.
• Armstrong numbers=1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208.
• Example: 153= 1*1*1*+5*5*5+3*3*=153 its Armstrong Number.
Code:
public class ArmstrongNumber {
public static void main(String[] args) {
int number = 371;
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
public static boolean isArmstrong(int number) {
int temp = number;
int digitCount = countDigits(number);
int sum = 0;
while (num > 0) {
int lastDigit= num % 10;
sum += power(lastDigit, digitCount);
temp /= 10;
}
return number == sum;
}
private static int countDigits(int number) {
int count = 0;
while (number > 0) {
count++;
number /= 10;
}
return count;
}
private static int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
} Output=371 is an Armstrong number
20. Check If a Number Is Disarium Number
• A Disarium number equals the sum of its digits raised to the power of
the position of digits.
• Armstrong numbers=1, 2, 3, 4, 5, 6, 7, 8, 9, 135, 175.
• Example: 153= 1*1+3*3+5*5*5=135 its Armstrong Number.
Java Code:
public class DisariumNumber {
public static void main(String[] args) {
int number = 371;
if (isArmstrong(number)) {
System.out.println(number + " is an Disarium number.");
} else {
System.out.println(number + " is not an Disarium number.");
}
}
public static boolean isDisarium (int number) {
int temp = number;
int digitCount = countDigits(number);
int sum = 0;
while (temp > 0) {
int digit = temp % 10;
sum += power(digit, digitCount);
digitCount--;
temp /= 10;
}
return number == sum;
}
private static int countDigits(int number) {
int count = 0;
while (number > 0) {
count++;
number /= 10;
}
Return count;
}
private static int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}} Output=153 is an Disarium number
21.Strong Number / Special Number / Krishnamurthy Number
• numbers where the sum of the factorials of their digits equals
the original number
• Example: 145 =1! +4! +5! =1+4*3*2*1+5*4*3*2*1=145
Java code:
public class StrongNumberCheck {
public static int factorial(int num) {
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sumFactorials = 0;
while (num > 0) {
int digit = num % 10;
sumFactorials += factorial(digit);
num /= 10;
}
return sumFactorials == originalNum;
}
public static void main(String[] args) {
int num = 145;
if (isStrongNumber(num)) {
System.out.println(num + " is a Strong Number");
} else {
System.out.println(num + " is NOT a Strong Number");
}
}
}

Output: 145 is a Strong Number


22. Spy Number
• A number where the sum of its digits equals the product of its digits
• Example: 123 → 1+2+3=6 and 1×2×3=6 (Spy).
Java Code:
public class SpyNumber {
public static boolean isSpy(int n) {
int sum = 0, product = 1;
while (n > 0) {
int d = n % 10;
sum += d;
product *= d;
n /= 10;
}
return sum == product;
}
public static void main(String[] args) {
int num = 123;
System.out.println("Is " + num + " a Spy number? " + isSpy(num));
}}
23.Harshad Number:
• A number divisible by the sum of its digits.
• Example: 18 → 1+8=9 → 18 ÷ 9 = 2 (Harshad)
Java Code:

public static boolean isHarshad(int n) {


int original = n;
int sum = 0;
while (n > 0) {
int d = n % 10;
sum += d;
n /= 10;
}
return original % sum == 0;
}
24. Check If a Number Is a Happy Number
• Repeat the sum of the squares of its digits until it reaches 1 or loops into a cycle
• Example: 19 → 1² + 9² = 82 → 8² + 2² = 68 → … → 1 (Happy).
• Java code:
public class HappyNumber {
public static boolean isHappy(int num) {
while (num != 1 && num != 4) {
num = sumOfSquares(num);
}
return num == 1;
}
public static int sumOfSquares(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
public static void main(String[] args) {
int number = 19;
System.out.println(number + " is a happy number? " + isHappy(number));
}
}
Output= 19 is a happy number? true;
25.Check If a Number Is a Magic Number
• A number is magic if the recursive sum of its digits equals 1.
• Example: 1729 → 1+7+2+9=19 → 1+9=10 → 1+0=1 (Magic).
Code:
public static boolean isMagic(int num) {
while (num > 9) {
num = sumOfDigits(num);
}
return num == 1;
}
public static int sumOfDigits(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit;
num /= 10;
}
return sum;
}

26.Duck Number:
• A number containing at least one zero, but not starting with zero
• 102 (contains 0, doesn’t start with 0)
• Java code:
public static boolean isDuck(int num) {
int firstDigit = num;
while (firstDigit >= 10) {
firstDigit /= 10;
}
boolean startsWithZero = (firstDigit == 0);
int temp = num;
boolean containsZero = false;
while (temp > 0) {
if (temp % 10 == 0) {
containsZero = true;
break;
}
temp /= 10;
}
return containsZero && !startsWithZero;
}
27.Perfect Numbers
• A perfect number equals the sum of its proper divisors
• Example: 6=1+2+3.

Code:
public class PerfectNumber {
public static boolean isPerfect(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) sum += i;
}
return sum == num;
}
public static void main(String[] args) {
int number = 6; // Example
System.out.println(number + " is a perfect number? " + isPerfect(number));
}
}
Output=true

28. Abundant Numbers


• An abundant number has the sum of its divisors greater than the number itself
• Example: 12: 1+2+3+4+6= 16.
public class AbundantNumber {
public static boolean isAbundant(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) sum += i;
}
return sum > num;
}
public static void main(String[] args) {
int number = 12; // Example
System.out.println(number + " is an abundant number? " + isAbundant(number));
}
}
Output=Flase
29.Pronic Number:
• Definition: A number that is the product of two consecutive integers
• Example: 6 = 2 × 3 (Pronic).
Java Code:
public class PronicNumber {
public static boolean isPreonic(int n) {
for (int k = 0; k <= (int) Math.sqrt(n); k++)
if (k * (k + 1) == n)
return true;
return false;
}
public static void main(String[] args) {
int num = 6;
System.out.println("Is " + num + " a Preonic number? " + isPreonic(num));
}
}

30.Amicable Numbers:
• Two numbers where each is the sum of the proper divisors of the other.
• Example: 220 and 284 (sum of divisors of 220 = 284, and vice versa).
• Java Code:
public class AmicableNumbers {
public static int sumProperDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++)
if (n % i == 0) sum += i;
return sum;
}
public static boolean areAmicable(int a, int b) {
return sumProperDivisors(a) == b && sumProperDivisors(b) == a && a != b;
}
public static void main(String[] args) {
int num1 = 220, num2 = 284;
System.out.println("Are " + num1 + " and " + num2 + " Amicable? " +
areAmicable(num1, num2));
}
}
31.Automorphic Number
• A number whose square ends with the number itself.
• Example: 25 → 25² = 625 (ends with 25)
• Java Code:
public class AutomorphicNumber {
public static boolean isAutomorphic(int n) {
long square = (long) n * n;
String numStr = Integer.toString(n);
return Long.toString(square).endsWith(numStr);
}
public static void main(String[] args) {
int num = 25;
System.out.println("Is " + num + " Automorphic? " + isAutomorphic(num));
}
}

32. Buzz Number:


• A number that ends with 7 or is divisible by 7.
• 14 (divisible by 7).
• Java Code:
public class BuzzNumber {
public static boolean isBuzz(int n) {
return n % 10 == 7 || n % 7 == 0;
}
public static void main(String[] args) {
int num = 14;
System.out.println("Is " + num + " a Buzz number? " + isBuzz(num));
}
}
33.Unique Number
• A number with all distinct digits.
• 123 (all digits unique).
• Java Code:
public class UniqueNumber {
public static boolean isUnique(int n) {
Set<Character> digits = new HashSet<>();
String numStr = Integer.toString(n);
for (char c : numStr.toCharArray()) {
if (digits.contains(c)) return false;
digits.add(c);
}
return true;
}
public static void main(String[] args) {
int num = 123;
System.out.println("Is " + num + " Unique? " + isUnique(num));
}
}
34.Ugly Number
• A number whose only prime factors are 2, 3, or 5
• 6 (factors: 2 × 3).
• Java Code:
public class UglyNumber {
public static boolean isUgly(int n) {
if (n <= 0) return false;
while (n % 2 == 0) n /= 2;
while (n % 3 == 0) n /= 3;
while (n % 5 == 0) n /= 5;
return n == 1;
}
public static void main(String[] args) {
int num = 6;
System.out.println("Is " + num + " Ugly? " + isUgly(num));
}
}
35.Find the nth Term of an Arithmetic Progression (AP)
• Formula: an=a+(n−1)×d.
public class AP {
public static int nthTermAP(int a, int d, int n) {
return a + (n - 1) * d;
}

public static void main(String[] args) {


System.out.println("5th term in AP: " + nthTermAP(2, 3, 5));
}
}

Output=

36. Find the nth Term of a Geometric Progression (GP)

• Formula: an=a×rn−1

Code:
public class GP {
public static double nthTermGP(int a, int r, int n) {
return a * Math.pow(r, n - 1);
}

public static void main(String[] args) {


System.out.println("4th term in GP: " + nthTermGP(3, 2, 4));
}
}
Advanced Challenge Questions for Number Problems

➢ Circular Prime

➢ Co-Prime Numbers

➢ Capricorn/Kaprekar Number

➢ Find the Smallest and Largest Digit in each number.

➢ Check if a number is an Automorphic number (76 → 76² = 5776, ends with 76).

➢ Determine if a number is a Spy number (Sum of digits equals the product of digits,

e.g. (1124 → 1+1+2+4 = 1×1×2×4).

➢ Write a program to identify if a number is a Fascinating number (192 → 192, 384,

576 concatenated = 192384576 contains all digits from 1-9 exactly once).

➢ Determine the nth number in Pascal’s triangle.

➢ Find the number of trailing zeros in the factorial of a number.

➢ Check if a number can be expressed as the sum of consecutive integers.

➢ Find the sum of digits raised to the power of their respective positions

➢ (e.g., 135 → 1¹ + 3² + 5³)


Array Manipulations Programs

Introduction to Array in Java:


An array in Java is a collection of elements of the same data type stored in
contiguous memory locations and fixed size. It allows storing multiple values
under a single variable name, accessed using an index.
Why Use Arrays?
Instead of declaring multiple variables, we can store multiple values in a single
array. Arrays provide fast access to elements using an index.
Useful for storing large amounts of data efficiently.

Memory Representation of an Array


When an array is created, it is allocated a block of memory in a contiguous manner.
Each element is stored in sequential memory locations.
Every element in the array is accessed using an index, starting from 0.
For example:
int [] numbers = {10, 20, 30, 40, 50};

Index 0 1 2 3 4
Value 10 20 30 40 50

To access the value 30, we use:


System.out.println(numbers[2]); // Output: 30

Types of Arrays in Java


1. One-Dimensional Array (1D Array)
2. Two-Dimensional Array (2D Array)
3. Jagged Array
1. One-Dimensional Array (1D Array)
A one-dimensional array stores elements in a single row.
Declaration and Initialization
int[] arr = new int[5]; // Declaration with size 5
arr[0] = 10; // Assigning values
arr[1] = 20;
Or, declare and initialize together:
int[] arr = {10, 20, 30, 40, 50};
Program 1D Array
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Array Elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
}
}
Output:
Array Elements: Index 0: 10 , Index 1: 20 , Index 2: 30 , Index 3: 40 , Index 4: 50

2. Two-Dimensional Array (2D Array)


A two-dimensional array stores data in a table (rows and columns).
Declaration and Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Program 2D Array
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("2D Array Elements:");
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();
}
}
}
Output:
2D Array Elements:
123
456
7 89
3Jagged Array:
A jagged array is a special type of 2D array where each row can have a different
number of columns.
Example of Jagged Array
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6}};
System.out.println("Jagged Array Elements:");
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Jagged Array Elements:
12
345
6

How Data is Stored and Fetched in an Array


1.Memory Allocation
• Arrays in Java are stored in heap memory.
• Each element is stored in a contiguous location.
• The reference variable points to the first element.
2.Fetching Data from an Array
• Data is accessed using an index.
• The first element is accessed at index 0, the second at 1, and so on.
• The length property is used to get the number of elements.
Example:
int[] arr = {5, 10, 15};
System.out.println(arr[0]); // Output: 5
System.out.println(arr[arr.length - 1]); // Output: 15 (last element)
1.Print all elements in an array:

Code:
public class PrintArray {
public static void printArray(int[] arr) {
System.out.print("Array Elements: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
printArray(array);
}
}
}

Output:
12345
2. Print array elements in reverse order:

Code:
public class ReverseOrder {
public static void printReverseArray(int[] arr) {
System.out.print("Reverse Array: ");
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
printReverseArray(array);
}
}
Output:
54321

3. Find Maximum Element:

Code:
public class FindMaxElement {
public static int findMax(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
return max;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println(findMax(array));
}
}
Output:5
4. Find the minimum element:

Code:
public class FindMinElement {
public static int findMin(int[] arr) {
int min = arr[0];
for (int num : arr) {
if (num < min) {
min = num;
}
}
return min;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println(findMin(array));
}
}
Output:1

5.Find Second Largest Element


Code:
public class Main {
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num < largest) {
secondLargest = num;
}
}
return secondLargest;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println(findSecondLargest(array));
}
}
Output:4
6.Find Second Smallest Element
Code:
public class Main {
public static int findSecondSmallest(int[] arr) {
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int num : arr) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num > smallest) {
secondSmallest = num;
}
}
return secondSmallest;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println(findSecondSmallest(array));
}
} Output:2
7.Find Count Frequency of Number
Code:
public class Main {
public static void countFrequency(int[] arr) {
boolean[] visited = new boolean[arr.length];
System.out.println("Element Frequencies:");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) {
continue;
}
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
visited[j] = true;
}
System.out.prin }
tln(arr[i] + " -> " + count + " times");
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5,1,5,3,4,6,7,6,9};
countFrequency(array);
}
}
Output:
Element Frequencies:
1 -> 2 times
2 -> 1 times
3 -> 2 times
4 -> 2 times
5 -> 2 times
6 -> 2 times
7 -> 1 times
9 -> 1 times
8.Find Count Even Odd
Code:
public class Main {
public static void CountEvenOdd (int[] arr) {
int evenCount=0;
int oddCount=0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
evenCount++; // Skip if already counted
}else{
oddCount++;
}
}
System.out.println("even Count -> " + evenCount + " times");
System.out.println("odd Count -> " + oddCount + " times");
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5,1,5,3,4,6,7,6,9};
CountEvenOdd(array);
}
}
Output:
even Count -> 5 times
odd Count -> 8 times
9. Find and Print Unique Elements
Code:
public class UniqueElements {
public static void printUniqueElements(int[] arr) {
boolean[] visited = new boolean[arr.length];

System.out.println("Unique Elements:");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) {
continue;
}

boolean isUnique = true;


for (int j = 0; j < arr.length; j++) {
if (i != j && arr[i] == arr[j]) {
isUnique = false;
visited[j] = true;
}
}

if (isUnique) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5,1,5,3,4,6,7,6,9};
printUniqueElements(array);
}
}
Output:
Unique Elements:
2
7
9

.
10. Find and Print Duplicate Elements
Code:
public class DuplicateElements {

public static void printDuplicates(int[] arr) {


boolean[] visited = new boolean[arr.length];

System.out.println("Duplicate Elements:");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) {
continue;
}

boolean isDuplicate = false;


for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
isDuplicate = true;
visited[j] = true;
}
}

if (isDuplicate) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5,1,5,3,4,6,7,6,9};
printDuplicates(array);
}
}

Output:
Duplicate Elements:
1
3
4
5
6
Sorting Algorithm
11. Bubble Sort
Bubble Sort is a basic sorting algorithm that works by repeatedly swapping adjacent elements
if they are in the wrong order. This process continues until the entire array is sorted.

How Bubble Sort Works?


• The algorithm makes multiple passes over the array.
• In each pass, it compares adjacent elements and swaps them if needed.
• The largest element "bubbles" to its correct position at the end after each pass.
• The process repeats until the array is fully sorted.

Example: Sorting [4, 1, 5, 2, 3] using Bubble Sort


Pass 1:
1. [4, 1, 5, 2, 3] Compare 4 and 1. Swap since 4 > 1. Result: [1, 4, 5, 2, 3]
2. [1, 4, 5, 2, 3] Compare 4 and 5. No swap needed.
3. [1, 4, 5, 2, 3] Compare 5 and 2. Swap since 5 > 2. Result: [1, 4, 2, 5, 3]
4. [1, 4, 2, 5, 3] Compare 5 and 3. Swap since 5 > 3. Result: [1, 4, 2, 3, 5] (5 is now sorted)
Result after Pass 1 → [1, 4, 2, 3, 5]
Pass 2:
1. [1, 4, 2, 3, 5] Compare 1 and 4. No swap needed.
2. [1, 4, 2, 3, 5] Compare 4 and 2. Swap since 4 > 2. Result: [1, 2, 4, 3, 5]
3. [1, 2, 4, 3, 5] Compare 4 and 3. Swap since 4 > 3. Result: [1, 2, 3, 4, 5] (4 is now sorted)
Result after Pass 2 → [1, 2, 3, 4, 5]
Pass 3:
1. [1, 2, 3, 4, 5] Compare 1 and 2. No swap needed.
2. [1, 2, 3, 4, 5] Compare 2 and 3. No swap needed.
Result after Pass 3 → [1, 2, 3, 4, 5]
Pass 4:
1. [1, 2, 3, 4, 5] Compare 1 and 2. No swap needed.
Since no swaps were made, the array is now fully sorted!
Final Sorted Array: [1, 2, 3, 4, 5]
Code:
public class BubbleSort {
public static void bubbleSorts(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
}
}
public static void printArray(int[] arr) {
System.out.print("[ ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println("]");
}

public static void main(String[] args) {


int arr[] = { 4, 1, 5, 2, 3 };
System.out.println("Before sorting:");
printArray(arr);
bubbleSort(arr);
System.out.println("After sorting:");
printArray(arr);
}

}
Input:4 1 5 2 3
Output:
Before sorting:
[ 4 1 5 2 3]
After sorting:
[ 1 2 3 4 5]
Bubble Sort (Optimized)

Optimized Approach

• We introduce a swapped flag to track if any swaps were made in a pass.


• If no swaps occur in a full pass, the array is already sorted, and we exit early.

public class BubbleSort {


public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
public static void printArray(int[] arr) {
System.out.print("[ ");

for (int num : arr) {


System.out.print(num + " ");
}
System.out.println("]");
}
public static void main(String[] args) {
int arr[] = { 4, 1, 5, 2, 3 };
System.out.println("Before sorting:");
printArray(arr);
bubbleSort(arr);
System.out.println("After sorting:");
printArray(arr);
}
}
12. Selection Sort
Selection Sort is a simple sorting algorithm that repeatedly selects the smallest element
from the unsorted portion of the array and swaps it with the first unsorted element.
How Selection Sort Works?
• The algorithm divides the array into a sorted and an unsorted region.
• It repeatedly selects the minimum element from the unsorted region.
• The selected element is swapped with the first unsorted element.
• The process repeats until the entire array is sorted.
Example: Sorting [4, 1, 5, 2, 3] using Selection Sort
Pass 1:
Select the smallest (1) and swap with 4 → [1, 4, 5, 2, 3]
Pass 2:
Select the smallest (2) and swap with 4 → [1, 2, 5, 4, 3]
Pass 3:
Select the smallest (3) and swap with 5 → [1, 2, 3, 4, 5]
Pass 4:
Select the smallest (4) (already in place)
Final Sorted Array: [1, 2, 3, 4, 5]
Code:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
} }
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int arr[] = { 4, 1, 5, 2, 3 };
System.out.println("Before sorting:");
printArray(arr);
selectionSort(arr);
System.out.println("After sorting:");
printArray(arr);
}
}
13. Insertion Sort
Insertion sort builds the sorted array one element at a time by comparing it with
already sorted elements.

How Insertion Sort Works?


• It builds a sorted array one element at a time.
• Each new element is compared to the sorted portion and inserted at the correct
position.
• This process continues until the array is sorted.

Example: Sorting [4, 1, 5, 2, 3] using Insertion Sort


Pass 1:
4 is already sorted → [4, 1, 5, 2, 3]
Pass 2:
Insert 1 in sorted portion → [1, 4, 5, 2, 3]
Pass 3:
5 is already in place → [1, 4, 5, 2, 3]
Pass 4:
Insert 2 in sorted portion → [1, 2, 4, 5, 3]
Pass 5:
Insert 3 in sorted portion → [1, 2, 3, 4, 5]
Final Sorted Array: [1, 2, 3, 4, 5]
Code:
public class InsertionSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
sort( array);
printArray(array);
}
}
Output: 11 12 22 25 64
14. Quick Sort
Quick sort is a divide-and-conquer algorithm that partitions the array around a pivot.

Code:
public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 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++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
sort(array,0,array.length-1);
printArray(array);
}
}
Output:
11 12 22 25 64
Searching Algorithms
15. Linear Search
Linear search involves traversing the array from the beginning to the end to find the
target element.

Code:
public class LinearSearch {
public static int search(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}

public static void printResult(int result, int target) {


if (result != -1) {
System.out.println("Element " + target + " found at index: " + result);
} else {
System.out.println("Element " + target + " not found.");
}
}

public static void main(String[] args) {


int[] unsortedArray = {64, 34, 25, 12, 22, 11, 90};
int target = 22;
int linearResult =search(unsortedArray, target);
printResult(linearResult, target);
}
}

Output:
Element 22 found at index: 4
16. Binary Search
Binary search divides the search space in half repeatedly. This works only on sorted
arrays.
Code:
public class BinarySearch{
public static int search(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;

while (low <= high) {


int mid = low + (high - low) / 2;

if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return -1;
}

public static void printResult(int result, int target) {


if (result != -1) {
System.out.println("Element " + target + " found at index: " + result);
} else {
System.out.println("Element " + target + " not found.");
}
}

public static void main(String[] args) {


int[] sortedArray = {11, 12, 22, 25, 34, 64, 90};
int target = 22;
int linearResult =search(sortedArray, target);
printResult(linearResult, target);
}
}

Output:
Element 22 found at index: 2
17.calculateAllSubarraySums(array)
To calculate the sum of all subarrays, iterate over all possible subarrays and
calculate their sums
Code:
public class SubarraySum {
public static void calculateAllSubarraySums(int[] arr) {
System.out.println("Sum of all subarrays:");
int totalSum = 0;
for (int i = 0; i < arr.length; i++) {
int currentSum = 0;
for (int j = i; j < arr.length; j++) {
currentSum += arr[j];
totalSum += currentSum;
System.out.println("Subarray [" + i + ", " + j + "] Sum: " + currentSum);
}
}
System.out.println("Total sum of all subarrays: " + totalSum);
}
public static void main(String[] args) {
int[] arr = {1, -2, 3, 4, -1, 2, -5, 4};
calculateAllSubarraySums(arr);
}
}
Output:
Subarray [0, 0] Sum: 1 Subarray [2, 4] Sum: 6
Subarray [0, 1] Sum: -1 Subarray [2, 5] Sum: 8
Subarray [0, 2] Sum: 2 Subarray [2, 6] Sum: 3
Subarray [0, 3] Sum: 6 Subarray [3, 3] Sum: 4
Subarray [0, 4] Sum: 5 Subarray [3, 4] Sum: 3
Subarray [0, 5] Sum: 7 Subarray [3, 5] Sum: 5
Subarray [0, 6] Sum: 2 Subarray [3, 6] Sum: 0
Subarray [0, 7] Sum: 6 Subarray [3, 7] Sum: 4
Subarray [1, 1] Sum: -2 Subarray [4, 4] Sum: -1
Subarray [1, 2] Sum: 1 Subarray [4, 5] Sum: 1
Subarray [1, 3] Sum: 5 Subarray [4, 6] Sum: -4
Subarray [1, 4] Sum: 4 Subarray [4, 7] Sum: 0
Subarray [1, 5] Sum: 6 Subarray [5, 5] Sum: 2
Subarray [1, 6] Sum: 1 Subarray [5, 6] Sum: -3
Subarray [1, 7] Sum: 5 Subarray [5, 7] Sum: 1
Subarray [2, 2] Sum: 3 Subarray [6, 6] Sum: -5
Subarray [2, 3] Sum: 7 Subarray [6, 7] Sum: -1
Subarray [7, 7] Sum: 4

Total sum of all subarrays: 92


18. Find the subarray with the maximum sum (Kadane’s Algorithm)
Kadane’s Algorithm efficiently finds the maximum sum of a subarray in O(n) time.

Code:
public class MaximumSubarraySum {
public static int findMaximumSubarraySum(int[] arr) {
int maxCurrent = arr[0];
int maxGlobal = arr[0];

for (int i = 1; i < arr.length; i++) {


maxCurrent = Math.max(arr[i], maxCurrent + arr[i]);
if (maxCurrent > maxGlobal) {
maxGlobal = maxCurrent;
}
}
return maxGlobal;
}
public static void main(String[] args) {
int[] arr = {1, -2, 3, 4, -1, 2, -5, 4};
int maxSum =findMaximumSubarraySum(arr);
System.out.println("\nMaximum sum of a subarray: " + maxSum);
}
}

Output:

Maximum sum of a subarray: 8


Introduction to 2D Arrays

1. What is a 2D Array?

A 2D array is a grid (or table) of elements arranged in rows and columns.


• Think of it as an array of arrays, where each row is a 1D array.

• Real-world analogy: A building where:

o Each floor (row) has multiple rooms (columns).

o The entire building is the 2D array

2. Declaring a 2D Array

Syntax:

dataType[][] arrayName = new dataType[rows][columns];

Example:

String[][] building = new String[3][4]; // 3 floors, 4 rooms each

3. Initializing a 2D Array
Option 1: Direct initialization
String[][] building = {
{"Room 101", "Room 102", "Room 103"}, // Floor 0
{"Room 201", "Room 202", "Room 203"}, // Floor 1
{"Room 301", "Room 302", "Room 303"} // Floor 2
};

Option 2: Assign values later

building[0][0] = "Room 101"; // Floor 0, Room 0


building[1][2] = "Room 203"; // Floor 1, Room 2

4. Accessing Elements
• Use two indices: [floor][room].
• Example:
System.out.println(building[1][2]); // Output: "Room 203"
Challenge Questions for Students
1. Find the Median:
o Given an unsorted array, find its median.

2. Rotate an Array:
o Rotate the array by k positions to the left or right.

3. Sort an Array of 0s, 1s, and 2s:


o Without using any sorting algorithm.

4. Find the Missing Number:


o In a given array of size n-1 with numbers 1 to n.

5. Rearrange Alternately:
o Rearrange an array such that the first element is the largest, the second is

the smallest,
and so on.
6. Product Array:
o Create an array where each element is the product of all elements in the

original array except itself (without using division).


7. Find Triplets with Zero Sum:
o Check if there exist three elements in an array whose sum is zero.

8. Check Palindromic Array:


o Determine if the array forms a palindrome.

9. Find the First Repeating Element:


o Find the first element that repeats in the array.

10. Find Majority Element:


o Find the element that appears more than n/2 times in an array (if any).

11. Sort by Frequency:


o Sort elements of an array by frequency of their occurrence.

12. Smallest Subarray with Given Sum:


o Find the smallest contiguous subarray whose sum is greater than or equal

to a given number.
13. Check if Array is Sorted:
o Write a program to verify if an array is sorted.

14. Find the Leader Elements:


o An element is a leader if it is greater than all the elements to its right.

15. Find the Kth Largest Element:


o Find the kth largest element in an unsorted array.
String Manipulations Program
1.Reversing a String:

Method 1:
Code:

class Main {
public static void main(String[] args) {
String str="java";
String reverse="";
for(int i=0; i<str.length(); i++){
reverse=str.charAt(i)+reverse;
}
System.out.println(reverse);
}
}

Input:java
Output:avaj

Method 2:
Code:

class Main {
public static void main(String[] args) {
String str="java";
String reverse="";
for(int i= str.length()-1; i>=0; i--){
reverse+=str.charAt(i);
}
System.out.println(reverse);
}
}

Input:java
Output:avaj
Method 3:
Code:

public class ReverseStringArray {


class Main {
public static String reverse(String str) {
char[] charArray = str.toCharArray();
int left = 0, right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right--;
}
return new String(charArray);
}
public static void main(String[] args) {
String str="java";
System.out.println( reverse(str));
}
}
Input:java
Output:avaj

Method 4:
Code:

public class ReverseStringArray {

public static void main(String[] args) {


StringBuilder stringBuilder = new StringBuilder("java");
String reverse = stringBuilder.reverse().toString();
System.out.println(reverse);
}
}

Input:java
Output:avaj
2. Checking for Palindromes:
Method 1:
class Main {
public static void main(String[] args) {
String str = "java";
String reverse = "";
for (int i = 0; i < str.length(); i++) {
reverse = str.charAt(i) + reverse;
}
if (str.equals(reverse)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
Input:java Output:avaj
Method 2:
class Main {
public static void main(String[] args) {
String str = "radar"; // Input string
if (isPalindrome(str)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Output: radar;
3. Converting Cases (Uppercase/Lowercase/ ToggleCase)
Code:
public class CaseConversion {

public String toUpperCase(String str) {


return str.toUpperCase();
}

public String toLowerCase(String str) {


return str.toLowerCase();
}

public String toggleCase(String str) {


StringBuilder toggled = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
toggled.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
toggled.append(Character.toUpperCase(c));
} else {
toggled.append(c); // Non-alphabetic characters remain unchanged
}
}
return toggled.toString();
}

public static void main(String[] args) {


CaseConversion caseConverter = new CaseConversion();
String str = "Hello World!";

System.out.println("Original: " + str);


System.out.println("Uppercase: " + caseConverter.toUpperCase(str));
System.out.println("Lowercase: " + caseConverter.toLowerCase(str));
System.out.println("Toggled Case: " + caseConverter.toggleCase(str));
}
}
Output:
Original: Hello World!
Uppercase: HELLO WORLD!
Lowercase: hello world!
Toggled Case: hELLO wORLD!
4. Removing Duplicates
Code:
public class RemoveDuplicates {
public String removeDuplicates(String str) {
String result = "";
boolean[] seen = new boolean[256];
for (char c : str.toCharArray()) {
if (!seen[c]) {
result += c;
seen[c] = true;
}
}
return result;
}
public static void main(String[] args) {
RemoveDuplicates remover = new RemoveDuplicates();
String str = "programming";
System.out.println("Original: " + str);
System.out.println("Without Duplicates: " + remover.removeDuplicates(str));
}
}
Output:
Original: programming
Without Duplicates: progamin
Method 2:
public static String removeDuplicates(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
boolean isDuplicate = false;
for (int j = 0; j < i; j++) {
if (str.charAt(i) == str.charAt(j)) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
result += str.charAt(i);
}
}
return result;
}
5.Character Frequency Count

Code:
public class CharacterFrequency {
public void countCharacterFrequency(String str) {
int[] frequency = new int[256];
for (char c : str.toCharArray()) {
frequency[c]++;
}
System.out.println("Character Frequency:");
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0) {
System.out.println((char) i + ": " + frequency[i]);
}
}
}
public static void main(String[] args) {
CharacterFrequency counter = new CharacterFrequency();
String str = "programming";

System.out.println("Input String: " + str);


counter.countCharacterFrequency(str);
}
}

Output: Input String: programming


Character Frequency: a: 1 g: 2 i: 1 m: 2 n: 1o: 1p: 1r: 2
6.Count Vowels And Consonants

Code:
public class VowelConsonantCounter {

public static void countVowelsAndConsonants(String str) {


int vowels = 0, consonants = 0;
str = str.toLowerCase();
for (char c : str.toCharArray()) {
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Total Vowels: " + vowels);
System.out.println("Total Consonants: " + consonants);
}
public static void main(String[] args) {
String str = "Hello World!";
countVowelsAndConsonants(str);
}
}
Output:
Input String: Hello World!
Total Vowels: 3
Total Consonants: 7
7. Anagram Checking
Code:
Method 1: witho using array sorting
public class AnagramCheck {

public static boolean areAnagrams(String str1, String str2) {


str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
if (str1.length() != str2.length()) {
return false;
}
int[] charCount = new int[256];

for (char c : str1.toCharArray()) {


charCount[c]++;
}
for (char c : str2.toCharArray()) {
charCount[c]--;
}
for (int count : charCount) {
if (count != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "Silent";

if (areAnagrams(str1, str2)) {
System.out.println("\"" + str1 + "\" and \"" + str2 + "\" are anagrams.");
} else {
System.out.println("\"" + str1 + "\" and \"" + str2 + "\" are not anagrams.");
}
}
}
Output:
"Listen" and "Silent" are anagrams.
Method 2: with using array sorting
public static boolean areAnagrams(String str1, String str2) {
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();

if (str1.length() != str2.length()) {
return false;
}
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}

8. Remove All White Spaces


Code:
public class RemoveWhiteSpaces {

public String removeWhiteSpaces(String str) {


return str.replaceAll("\\s+", "");
}

public static void main(String[] args) {


RemoveWhiteSpaces remover = new RemoveWhiteSpaces();

String input = " Hello \t World \n Welcome to Java ";


System.out.println("Original String: \"" + input + "\"");

String result = remover.removeWhiteSpaces(input);


System.out.println("String Without White Spaces: \"" + result + "\"");
}
}
Output:
Original String: " Hello World
Welcome to Java "
String Without White Spaces: "HelloWorldWelcometoJava"
9.Write a program to find the length of a string without using a function

Code:
public class StringLengthWithoutFunction {

public static void main(String[] args) {


String str = "hello";
int length = 0;
for (char c : str.toCharArray()) {
length++;
}
System.out.println("Length of the string: " + length);
}
}
Output:5
10. Find Longest Word in a String
public class LongestWordFinder {
public String findLongestWord(String str) {
if (str == null || str.isEmpty()) {
return "";
}
String[] words = str.split("\\s+");
String longestWord = "";
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}
return longestWord;
}
public static void main(String[] args) {
LongestWordFinder finder = new LongestWordFinder();
String input = "The quick brown fox jumps over the lazy dog";
System.out.println("Input String: \"" + input + "\"");
System.out.println("Longest Word: \"" + finder.findLongestWord(input) + "\"");
}
}
Output:
Input String: "The quick brown fox jumps over the lazy dog"
Longest Word: "jumps"
11. Reverse Words in a Sentence
Code:
public class ReverseWords {

public String reverseWordsInSentence(String sentence) {


if (sentence == null || sentence.trim().isEmpty()) {
return "";
}

String[] words = sentence.trim().split("\\s+");


String reversedSentence = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedSentence += words[i];
if (i > 0) {
reversedSentence += " ";
}
}
return reversedSentence;
}
public static void main(String[] args) {
ReverseWords reverser = new ReverseWords();

String sentence = "The quick brown fox jumps over the lazy dog";
System.out.println("Original Sentence: \"" + sentence + "\"");
System.out.println("Reversed Words: \"" +
reverser.reverseWordsInSentence(sentence) + "\"");
}
}
Output:
Original Sentence: "The quick brown fox jumps over the lazy dog"
Reversed Words: "dog lazy the over jumps fox brown quick The"
12. Check if a String Contains Only Digits:
Code:
public class StringContainsDigits {

public boolean containsOnlyDigits(String str) {


if (str == null || str.isEmpty()) {
return false;
}

for (char c : str.toCharArray()) {


if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
StringContainsDigits checker = new StringContainsDigits();
String str1 = "123456";
String str2 = "1234a56";
String str3 = "";
String str4 = "9876543210";
System.out.println("Does \"" + str1 + "\" contain only digits? " +
checker.containsOnlyDigits(str1));
System.out.println("Does \"" + str2 + "\" contain only digits? " +
checker.containsOnlyDigits(str2));
System.out.println("Does \"" + str3 + "\" contain only digits? " +
checker.containsOnlyDigits(str3));
System.out.println("Does \"" + str4 + "\" contain only digits? " +
checker.containsOnlyDigits(str4));
}
}
Output:
Does "123456" contain only digits? true
Does "1234a56" contain only digits? false
Does "" contain only digits? false
Does "9876543210" contain only digits? True
Challenge Questions
1. Reverse Words in a Sentence
Reverse the order of words in a sentence without reversing the characters of each word.
E.g., Input: "Hello World" → Output: "World Hello"

2. Check Rotation of Strings


Determine if one string is a rotation of another.
E.g., Input: "abcd", "cdab" → Output: Yes

3. Count Palindromic Substrings


Count all substrings that are palindromes.

4. Longest Palindromic Substring


Find the longest substring in a string that is a palindrome.

5. Find and Replace a Substring


Replace all occurrences of a substring with another substring.

6. String Compression
Compress a string by replacing consecutive repeating characters with their count.
E.g., Input: "aaabbc" → Output: "a3b2c1"

7. Check if Two Strings are Isomorphic


E.g., Input: "foo", "bar" → Output: No

8. Remove All White Spaces


Remove all spaces, tabs, and newlines from a string.

9. String to Integer Conversion (Custom parseInt)


Convert a string representing a number into an integer without using built-in methods.

10. Decode a Run-Length Encoded String


Decode a string encoded using run-length encoding.
E.g., Input: "a3b2c1" → Output: "aaabbc"

11. String Segmentation Problem


Given a dictionary of words, check if a string can be segmented into valid dictionary words.
E.g., Input: "applepen", Dict: {"apple", "pen"} → Output: True

12. Pattern Matching with Strings (KMP Algorithm)


Implement Knuth-Morris-Pratt algorithm for efficient substring search.

13. Pattern Matching with Strings (Rabin-Karp Algorithm)


Use hash-based matching for substring search.

14. Find All Permutations of a String


Generate all permutations of a given string recursively.
Bitwise Operators
Bitwise operators in Java operate on individual bits of integer data types
(like int, long, etc.). These operators are commonly used in low-level programming,
such as bit manipulation, optimizing code, and working with hardware

Types of Bitwise Operators

Operator Description Example


& Bitwise AND a&b
| Bitwise OR a|b
^ Bitwise exclusive OR(XOR) a^b
~ Bitwise Complement (NOT) ~a
<< Left Shift a << n
>> Right Shift a >> n

• Bitwise AND (&)


1) Compares each bit of two numbers and returns 1 if both bits are 1 behaviour
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a & b; // Binary: 0001 (Decimal: 1)
System.out.println("a & b = " + result); // Output: 1

• Bitwise OR (|)
Compares each bit of two numbers and returns 1 if either bit is 1.
Examples: int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a | b; // Binary: 0111 (Decimal: 7)
System.out.println("a | b = " + result); // Output: 7

• Bitwise XOR (^)


Compares each bit of two numbers and returns 1 if the bits are different.
Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a ^ b; // Binary: 0110 (Decimal: 6)
System.out.println("a ^ b = " + result); // Output: 6
• Bitwise Complement (~)
Inverts all the bits of the number (changes 0 to 1 and 1 to 0).
Examples:

int a = 5; // Binary: 0101

int result = ~a; // Binary: 1010 (Decimal: -6 in 2's complement)

System.out.println("~a = " + result); // Output: -6

• Left Shift (<<)

Shifts bits to the left, filling with 0s on the right. Each shift multiplies

the number by 2.

Example:

int a = 5; // Binary: 0101

int result = a << 2; // Binary: 010100 (Decimal: 20)

System.out.println("a << 2 = " + result); // Output: 20

• Right Shift (>>)

Shifts bits to the right, keeping the sign bit (MSB) intact. Each shift divides the
number by 2

Example: int a = 5; // Binary: 0101

int result = a >> 1; // Binary: 0010 (Decimal: 2)

System.out.println("a >> 1 = " + result); // Output: 2


1.Checking if a Number is Odd or Even

int num = 5;

if ((num & 1) == 0) {

System.out.println(num + " is Even");

} else {

System.out.println(num + " is Odd");

} // Output: 5 is Odd

2. Swapping Two Numbers Without Using a Temporary Variable


public class BitwiseSwap {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
END

You might also like