0% found this document useful (0 votes)
10 views11 pages

Java Essential Programs Arrays Strings Numbers Generic

Uploaded by

mansoorsk115
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)
10 views11 pages

Java Essential Programs Arrays Strings Numbers Generic

Uploaded by

mansoorsk115
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

Java — Essential Repeated Programs (Arrays,

Strings, Numbers, Generic)


Purpose: A ready-to-print document that contains copy-pasteable Java programs commonly repeated in
coding assignments. Each program includes:

• A clean, copy-pasteable Java code block.


• A line-by-line explanation that maps to the code lines so you can learn exactly what each line does.
• Sample input / output where relevant.

To save as PDF: Use the canvas file menu or browser File → Print → Save as PDF .

Table of Contents
1. Arrays
2. 1.1 Find Maximum and Minimum in an Array
3. 1.2 Reverse an Array
4. 1.3 Check if Array is Sorted
5. Strings
6. 2.1 Palindrome String
7. 2.2 Count Vowels and Consonants
8. 2.3 Anagram Check
9. Numbers
10. 3.1 Prime Number Check
11. 3.2 Factorial of a Number
12. 3.3 Fibonacci Series
13. Generic Problem Solving
14. 4.1 Binary Search
15. 4.2 Linear Search
16. 4.3 Matrix Multiplication

1. ARRAYS
1.1 Find Maximum and Minimum in an Array

Code (copy-pasteable)

import java.util.*;

class MaxMinArray {

1
public static void main(String[] args) {
int[] arr = {5, 8, 1, 3, 9, 2};
int max = arr[0];
int min = arr[0];
for (int num : arr) {
if (num > max) max = num;
if (num < min) min = num;
}
System.out.println("Max: " + max + ", Min: " + min);
}
}

Line-by-line explanation

1. import java.util.*; — imports the Java utility package (not strictly required here but included
for completeness).
2. class MaxMinArray { — declares the class named MaxMinArray .
3. public static void main(String[] args) { — program entry point.
4. int[] arr = {5, 8, 1, 3, 9, 2}; — declares and initializes an integer array.
5. int max = arr[0]; — initialize max with the first element.
6. int min = arr[0]; — initialize min with the first element.
7. for (int num : arr) { — enhanced for-loop to iterate over each element num in arr .
8. if (num > max) max = num; — update max when a larger value is found.
9. if (num < min) min = num; — update min when a smaller value is found.
10. } — end of loop.
11. System.out.println("Max: " + max + ", Min: " + min); — print results.
12. } — end of main .
13. } — end of class.

1.2 Reverse an Array

Code (copy-pasteable)

class ReverseArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

2
Line-by-line explanation

1. class ReverseArray { — declares the class.


2. public static void main(String[] args) { — entry point.
3. int[] arr = {10, 20, 30, 40}; — declare and initialize array.
4. for (int i = arr.length - 1; i >= 0; i--) { — for-loop starting from last index down to
0.
5. System.out.print(arr[i] + " "); — print each element followed by a space (no newline until
the end).
6. } — end of loop.
7. } — end of main .
8. } — end of class.

1.3 Check if Array is Sorted

Code (copy-pasteable)

class CheckSorted {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
boolean sorted = true;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
sorted = false;
break;
}
}
System.out.println(sorted ? "Sorted" : "Not Sorted");
}
}

Line-by-line explanation

1. class CheckSorted { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int[] arr = {1, 2, 3, 4, 5}; — sample array.
4. boolean sorted = true; — assume array is sorted until proven otherwise.
5. for (int i = 1; i < arr.length; i++) { — iterate from second element to the end.
6. if (arr[i] < arr[i - 1]) { — if current element is less than previous, it's not sorted.
7. sorted = false; — set flag.
8. break; — exit early for efficiency.
9. } — end if.
10. } — end loop.
11. System.out.println(sorted ? "Sorted" : "Not Sorted"); — print result.

3
12. } — end main.
13. } — end class.

2. STRINGS
2.1 Palindrome String

Code (copy-pasteable)

class PalindromeString {
public static void main(String[] args) {
String s = "madam";
String rev = new StringBuilder(s).reverse().toString();
System.out.println(s.equals(rev) ? "Palindrome" : "Not Palindrome");
}
}

Line-by-line explanation

1. class PalindromeString { — declare class.


2. public static void main(String[] args) { — entry point.
3. String s = "madam"; — input string.
4. String rev = new StringBuilder(s).reverse().toString(); — create a
StringBuilder from s , reverse it, convert back to String .
5. System.out.println(s.equals(rev) ? "Palindrome" : "Not Palindrome"); — compare
original and reversed string and print.
6. } — end main.
7. } — end class.

2.2 Count Vowels and Consonants

Code (copy-pasteable)

class CountVowels {
public static void main(String[] args) {
String s = "Hello World";
s = s.toLowerCase();
int vowels = 0, consonants = 0;
for (char ch : s.toCharArray()) {
if ("aeiou".indexOf(ch) != -1) vowels++;
else if (ch >= 'a' && ch <= 'z') consonants++;

4
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
}
}

Line-by-line explanation

1. class CountVowels { — class declaration.


2. public static void main(String[] args) { — entry point.
3. String s = "Hello World"; — input string.
4. s = s.toLowerCase(); — normalize to lowercase to simplify checks.
5. int vowels = 0, consonants = 0; — counters.
6. for (char ch : s.toCharArray()) { — iterate each character.
7. if ("aeiou".indexOf(ch) != -1) vowels++; — check if ch is a vowel.
8. else if (ch >= 'a' && ch <= 'z') consonants++; — check if ch is an alphabetic
consonant.
9. } — end loop.
10. System.out.println("Vowels: " + vowels + ", Consonants: " + consonants); —
print counts.
11. } — end main.
12. } — end class.

2.3 Anagram Check

Code (copy-pasteable)

import java.util.*;

class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen", s2 = "silent";
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
System.out.println(Arrays.equals(a, b) ? "Anagram" : "Not Anagram");
}
}

Line-by-line explanation

1. import java.util.*; — import utilities (for Arrays ).


2. class AnagramCheck { — class declaration.
3. public static void main(String[] args) { — entry point.

5
4. String s1 = "listen", s2 = "silent"; — two input strings.
5. char[] a = s1.toCharArray(); — convert first string to char array.
6. char[] b = s2.toCharArray(); — convert second string.
7. Arrays.sort(a); — sort first char array.
8. Arrays.sort(b); — sort second char array.
9. System.out.println(Arrays.equals(a, b) ? "Anagram" : "Not Anagram"); — if sorted
arrays match they are anagrams.
10. } — end main.
11. } — end class.

3. NUMBERS
3.1 Prime Number Check

Code (copy-pasteable)

class PrimeCheck {
public static void main(String[] args) {
int n = 29;
boolean isPrime = true;
if (n <= 1) isPrime = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
System.out.println(isPrime ? "Prime" : "Not Prime");
}
}

Line-by-line explanation

1. class PrimeCheck { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int n = 29; — number to test.
4. boolean isPrime = true; — assume prime until shown otherwise.
5. if (n <= 1) isPrime = false; — 0 and 1 are not prime.
6. for (int i = 2; i <= Math.sqrt(n); i++) { — test divisors up to sqrt(n) for efficiency.
7. if (n % i == 0) { isPrime = false; break; } — if divisible then not prime.
8. } — end loop.
9. System.out.println(isPrime ? "Prime" : "Not Prime"); — print result.
10. } — end main.
11. } — end class.

6
3.2 Factorial of a Number

Code (copy-pasteable)

class Factorial {
public static void main(String[] args) {
int n = 5;
long fact = 1;
for (int i = 1; i <= n; i++) fact *= i;
System.out.println("Factorial: " + fact);
}
}

Line-by-line explanation

1. class Factorial { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int n = 5; — input number.
4. long fact = 1; — use long for larger results.
5. for (int i = 1; i <= n; i++) fact *= i; — multiply fact by each i from 1 to n .
6. System.out.println("Factorial: " + fact); — print result.
7. } — end main.
8. } — end class.

3.3 Fibonacci Series

Code (copy-pasteable)

class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
}
}
}

7
Line-by-line explanation

1. class Fibonacci { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int n = 10; — how many terms to print.
4. int a = 0, b = 1; — first two Fibonacci numbers.
5. for (int i = 0; i < n; i++) { — loop n times.
6. System.out.print(a + " "); — print current term.
7. int c = a + b; — compute next term.
8. a = b; — shift a forward.
9. b = c; — shift b forward.
10. } — end loop.
11. } — end main.
12. } — end class.

4. GENERIC PROBLEM SOLVING


4.1 Binary Search

Code (copy-pasteable)

class BinarySearch {
public static int search(int[] arr, int key) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
System.out.println("Index: " + search(arr, 7));
}
}

Line-by-line explanation

1. class BinarySearch { — class declaration.


2. public static int search(int[] arr, int key) { — search method header returning
index or -1.

8
3. int low = 0, high = arr.length - 1; — initialize pointers.
4. while (low <= high) { — loop while interval valid.
5. int mid = (low + high) / 2; — compute middle index.
6. if (arr[mid] == key) return mid; — found the key.
7. else if (arr[mid] < key) low = mid + 1; — search right half.
8. else high = mid - 1; — search left half.
9. } — end loop.
10. return -1; — not found.
11. } — end method.
12. public static void main(String[] args) { — entry point.
13. int[] arr = {1, 3, 5, 7, 9}; — sample sorted array.
14. System.out.println("Index: " + search(arr, 7)); — print search result.
15. } — end main.
16. } — end class.

4.2 Linear Search

Code (copy-pasteable)

class LinearSearch {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
int key = 30, index = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) { index = i; break; }
}
System.out.println(index == -1 ? "Not Found" : "Found at " + index);
}
}

Line-by-line explanation

1. class LinearSearch { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int[] arr = {10, 20, 30, 40}; — sample array.
4. int key = 30, index = -1; — key to find and index placeholder.
5. for (int i = 0; i < arr.length; i++) { — iterate through array.
6. if (arr[i] == key) { index = i; break; } — if found, store index and break.
7. } — end loop.
8. System.out.println(index == -1 ? "Not Found" : "Found at " + index); — print
result.
9. } — end main.
10. } — end class.

9
4.3 Matrix Multiplication (2x2 example)

Code (copy-pasteable)

class MatrixMultiplication {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
c[i][j] = 0;
for (int k = 0; k < 2; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Line-by-line explanation

1. class MatrixMultiplication { — class declaration.


2. public static void main(String[] args) { — entry point.
3. int[][] a = {{1, 2}, {3, 4}}; — first 2x2 matrix.
4. int[][] b = {{5, 6}, {7, 8}}; — second 2x2 matrix.
5. int[][] c = new int[2][2]; — result matrix initialized to zeros.
6. for (int i = 0; i < 2; i++) { — iterate rows of a .
7. for (int j = 0; j < 2; j++) { — iterate columns of b .
8. c[i][j] = 0; — initialize current cell (optional since default is 0).
9. for (int k = 0; k < 2; k++) { — inner loop for dot product.
10. c[i][j] += a[i][k] * b[k][j]; — accumulate multiplication.
11. } — end k-loop.
12. System.out.print(c[i][j] + " "); — print element.
13. } — end j-loop.
14. System.out.println(); — newline after each row.
15. } — end i-loop.
16. } — end main.
17. } — end class.

10
Final Notes
• All code blocks are copy-paste ready into a .java file. If you paste into an editor remember: one
public class per file may be required if you add public modifier – these are left package-private for
convenience.
• If you want additional programs (e.g., remove duplicates from array, rotate array, sieve of
Eratosthenes, gcd/lcm, string permutations, substring search), tell me which ones and I will add
them with the same line-by-line detail.

End of document.

11

You might also like