Java Program Notes
Java Program Notes
2 Patterns
3 Number
4 Strings
5 Arrays
6 Bitwise
7 Recursion
➢ 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
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
• Equal to (==)
• Not equal to (! =)
▪ Logical OR (||)
}
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)
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)
Output (Prefix):
Key Points
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.
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
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.");
}
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);
}
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
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
Iteration-wise Explanation:
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:
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();
}
}
}
Iteration-wise Explanation:
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();
}
}
}
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:
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();
}
}
}
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();
} }
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;
}
• 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
11.Power of a Number:
Java Code:
Output= 6
Method 2: Euclidean Algorithm (Iterative)
Base Template:
Most problems use this fundamental logic:
int num=1234;
int count=0;
while (num > 0) {
int lastDigit = num % 10;
count++;
num /= 10;
}
System.out.println("Number of digits: " + count);
• 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
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
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));
}
}
Output=
• 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);
}
➢ Circular Prime
➢ Co-Prime Numbers
➢ Capricorn/Kaprekar 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,
576 concatenated = 192384576 contains all digits from 1-9 exactly once).
➢ Find the sum of digits raised to the power of their respective positions
Index 0 1 2 3 4
Value 10 20 30 40 50
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
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
System.out.println("Unique Elements:");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) {
continue;
}
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 {
System.out.println("Duplicate Elements:");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) {
continue;
}
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.
}
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
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;
}
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;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
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
Code:
public class MaximumSubarraySum {
public static int findMaximumSubarraySum(int[] arr) {
int maxCurrent = arr[0];
int maxGlobal = arr[0];
Output:
1. What is a 2D Array?
2. Declaring a 2D Array
Syntax:
Example:
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
};
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.
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
to a given number.
13. Check if Array is Sorted:
o Write a program to verify if an array is sorted.
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:
Method 4:
Code:
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 {
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";
Code:
public class VowelConsonantCounter {
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);
}
Code:
public class StringLengthWithoutFunction {
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 {
6. String Compression
Compress a string by replacing consecutive repeating characters with their count.
E.g., Input: "aaabbc" → Output: "a3b2c1"
• 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
Shifts bits to the left, filling with 0s on the right. Each shift multiplies
the number by 2.
Example:
Shifts bits to the right, keeping the sign bit (MSB) intact. Each shift divides the
number by 2
int num = 5;
if ((num & 1) == 0) {
} else {
} // Output: 5 is Odd