[Go to site: main page, start]

0% found this document useful (0 votes)
18 views13 pages

Java Array and String Operations Guide

The document contains various Java programs demonstrating array and string manipulations, including initialization, summation, searching, sorting, and character analysis. Key functionalities include finding prime numbers, missing numbers, and palindrome checks, as well as methods for string validation and character frequency. Additionally, it summarizes methods used for array and string operations, detailing their purposes.

Uploaded by

nobithanobi155
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)
18 views13 pages

Java Array and String Operations Guide

The document contains various Java programs demonstrating array and string manipulations, including initialization, summation, searching, sorting, and character analysis. Key functionalities include finding prime numbers, missing numbers, and palindrome checks, as well as methods for string validation and character frequency. Additionally, it summarizes methods used for array and string operations, detailing their purposes.

Uploaded by

nobithanobi155
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

Array programs

1. Initialize Array

public class ArrayInitialization {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50}; // Initialize and store values
[Link]("Array elements:");
for (int num : arr) {
[Link](num + " ");
}
}
}

2. Sum of Array Elements Up to Key Value

public class SumUpToKey {


public static void main(String[] args) {
int[] arr = {5, 10, 15, 20, 25};
int key = 15, sum = 0;
for (int num : arr) {
sum += num;
if (num == key) break;
}
[Link]("Sum up to key value: " + sum);
}
}

3. Sum Up to a Given Index

public class SumUpToIndex {


public static void main(String[] args) {
int[] arr = {5, 10, 15, 20, 25};
int index = 3, sum = 0;
for (int i = 0; i <= index; i++) {
sum += arr[i];
}
[Link]("Sum up to index " + index + ": " + sum);
}
}

4. Prime Numbers in Array (Sum, Count, Print)

public class PrimeNumbers {


public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {


int[] arr = {3, 5, 8, 13, 17, 20, 23};
int sum = 0, count = 0;

[Link]("Prime numbers: ");


for (int num : arr) {
if (isPrime(num)) {
[Link](num + " ");
sum += num;
count++;
}
}
[Link]("\nSum of primes: " + sum);
[Link]("Count of primes: " + count);
}
}

5. Find Max and Min in an Array

import [Link];

public class MaxMin {


public static void main(String[] args) {
int[] arr = {3, 7, 2, 9, 4};
int max = [Link](arr).max().getAsInt();
int min = [Link](arr).min().getAsInt();
[Link]("Max: " + max + ", Min: " + min);
}
}

6. Find Second Largest Element

import [Link];

public class SecondLargest {


public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
[Link](arr);
[Link]("Second largest: " + arr[[Link] - 2]);
}
}

7. Sum of Any Two Values Equal to Key

public class PairSum {


public static void main(String[] args) {
int[] arr = {2, 7, 11, 15};
int key = 9;
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] + arr[j] == key) {
[Link]("Pair: " + arr[i] + ", " + arr[j]);
return;
}
}
}
}
}

8. Array Rotation by K Times

import [Link];
public class RotateArray {
public static void rotate(int[] arr, int k) {
int n = [Link];
k = k % n;
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[(i + k) % n] = arr[i];
}
[Link](temp, 0, arr, 0, n);
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
int k = 2;
rotate(arr, k);
[Link]("Rotated array: " + [Link](arr));
}
}

9. Find Missing Number in an Array

public class MissingNumber {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
int n = [Link] + 1;
int sum = n * (n + 1) / 2;
for (int num : arr) {
sum -= num;
}
[Link]("Missing number: " + sum);
}
}

10. Binary Search

import [Link];

public class BinarySearch {


public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) left = mid + 1;
else right = mid - 1;
}
return -1;
}

public static void main(String[] args) {


int[] arr = {2, 3, 4, 10, 40};
int key = 10;
[Link]("Element found at index: " + binarySearch(arr, key));
}
}

11. Sorting (Basic - Bubble Sort)

import [Link];

public class BubbleSort {


public static void bubbleSort(int[] arr) {
int n = [Link];
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;
}
}
}
}

public static void main(String[] args) {


int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
[Link]("Sorted array: " + [Link](arr));
}
}

12. Longest Increasing Subsequence


import [Link];

public class LongestSubsequence {


public static int longestIncreasingSubsequence(int[] arr) {
int n = [Link];
int[] lis = new int[n];
[Link](lis, 1);

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


for (int j = 0; j < i; j++) {
if (arr[i] > arr[j] && lis[i] < lis[j] + 1) {
lis[i] = lis[j] + 1;
}
}
}
return [Link](lis).max().getAsInt();
}
public static void main(String[] args) {
int[] arr = {10, 22, 9, 33, 21, 50, 41, 60};
[Link]("Longest Increasing Subsequence Length: " +
longestIncreasingSubsequence(arr));
}
}

Method Used Purpose


length Get the length of the array
[Link](arr) Sort the array in ascending order
[Link](arr, key) Search for an element in a sorted array
[Link](arr1, arr2) Compare two arrays for equality
[Link](arr, newLength) Create a copy of an array with a new length
[Link](arr, from, to) Copy a subarray from arr[from] to arr[to-1]
[Link](arr, value) Fill the entire array with a given value
[Link](arr) Convert an array to a string for easy printing
[Link](arr) Convert an array into a List
[Link](arr).max().getAsInt() Get the maximum value from an array
Method Used Purpose
[Link](arr).min().getAsInt() Get the minimum value from an array

String Programs
1. Count of Vowels & Consonants (Using charAt())

public class VowelConsonantCount {


public static void main(String[] args) {
String str = "I have a TCS exam tomorrow".toLowerCase();
int vowels = 0, consonants = 0;

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);
if ([Link](ch)) {
if ("aeiou".contains([Link](ch))) vowels++;
else consonants++;
}
}

[Link]("Vowels: " + vowels);


[Link]("Consonants: " + consonants);
}
}

2. Password Validation (Using contains(), length())

public class PasswordValidation {


public static boolean isValidPassword(String password) {
return [Link]() >= 8 && [Link](".*[A-Z].*") &&
[Link](".*[a-z].*") && [Link](".*\\d.*") &&
[Link](".*[@#$%^&+=].*");
}

public static void main(String[] args) {


String password = "Pass@123";
[Link]([Link]("@") && isValidPassword(password) ? "Valid Password"
: "Invalid Password");
}
}

3. Palindrome Check (Using equals(), substring())

public class PalindromeCheck {


public static boolean isPalindrome(String str) {
return [Link](new StringBuilder(str).reverse().toString());
}

public static void main(String[] args) {


String str = "Level";
[Link](isPalindrome(str) ? "Palindrome" : "Not a Palindrome");
}
}

4. First Non-Repeating Character (Using indexOf(), substring())

public class FirstNonRepeatingChar {


public static void main(String[] args) {
String str = "aabbcdddeefg";
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch) == [Link](ch)) {
[Link]("First Non-Repeating Character: " + ch);
return;
}
}
}
}

5. Most Repeated Character in a String (Using indexOf())

public class MostRepeatedCharacter {


public static void main(String[] args) {
String str = "aabbcdddeefg";
int maxCount = 0;
char maxChar = ' ';

for (char ch : [Link]()) {


int count = [Link]() - [Link]([Link](ch), "").length();
if (count > maxCount) {
maxCount = count;
maxChar = ch;
}
}
[Link]("Most Repeated Character: " + maxChar);
}
}

6. Frequency of Each Character (Using indexOf(), substring())

public class CharacterFrequency {


public static void main(String[] args) {
String str = "hello world";
while (![Link]()) {
char ch = [Link](0);
int count = [Link]() - [Link]([Link](ch), "").length();
[Link](ch + ": " + count);
str = [Link]([Link](ch), "");
}
}
}

7. Remove Duplicates from a String (Using contains(), substring())

public class RemoveDuplicates {


public static void main(String[] args) {
String str = "level", result = "";
for (int i = 0; i < [Link](); i++) {
if (![Link]([Link]([Link](i)))) {
result += [Link](i);
}
}
[Link]("After Removing Duplicates: " + result);
}
}

8. Longest Substring Without Repeating Characters (Using substring())

public class LongestUniqueSubstring {


public static String longestUniqueSubstr(String str) {
String longest = "", current = "";
for (int i = 0; i < [Link](); i++) {
if ([Link]([Link]([Link](i)))) {
current = [Link]([Link]([Link](i)) + 1);
}
current += [Link](i);
if ([Link]() > [Link]()) longest = current;
}
return longest;
}
public static void main(String[] args) {
String str = "Banana";
[Link]("Longest Unique Substring: " + longestUniqueSubstr(str));
}
}

9. Check if Two Strings are Anagrams (Using split(), equals())

import [Link];

public class AnagramCheck {


public static boolean areAnagrams(String str1, String str2) {
char[] arr1 = [Link]();
char[] arr2 = [Link]();
[Link](arr1);
[Link](arr2);
return [Link](arr1, arr2);
}

public static void main(String[] args) {


String str1 = "net", str2 = "ten";
[Link](areAnagrams(str1, str2) ? "Yes, Anagrams" : "No, Not Anagrams");
}
}

10. Print All Words in Dictionary Order (Using split(), equals())

import [Link];

public class DictionaryOrder {


public static void main(String[] args) {
String words = "apple banana orange grape";
String[] arr = [Link](" ");
[Link](arr);
[Link]("Words in Dictionary Order: " + [Link](", ", arr));
}
}
Summary of Used Methods
Method Used Purpose
length() Get length of string
charAt(i) Get character at index i
indexOf(ch) Find first occurrence of character
substring(i, j) Extract part of string
contains(str) Check if string contains substring
split(" ") Split string into array
equals() Compare strings
toLowerCase() Convert to lowercase
toUpperCase() Convert to uppercase

Common questions

Powered by AI

The `LongestUniqueSubstring` program uses a sliding window technique to iterate through the string, maintaining a current substring without repeating characters. It uses a string `current` to track the valid substring and resets it from the character after a duplicate is found. It updates the `longest` substring if the current one is longer. This improves performance by maintaining a continuous substring instead of constructing substrings from scratch repetitively, potentially reducing complexity over a naive O(n^2) solution to a more efficient O(n).

The `SumUpToKey` program sums the elements of the array until it encounters an element that matches the specified key value. If the key is found, the loop breaks, and the sum of elements up to and including the key is printed. If the key value is not present in the array, the program will continue to sum all elements without breaking, resulting in the total sum of the array elements being printed .

The `BinarySearch` algorithm works by repeatedly dividing the search interval in half, comparing the middle element of the array with the target key. If the middle element equals the key, it returns the index; otherwise, it narrows the search to the lower or upper half, depending on whether the key is smaller or larger than the middle element. This method requires the array to be sorted and has a time complexity of O(log n). Its limitation is that it only works with sorted arrays, and if applied to an unsorted array, it may fail to find the key or produce incorrect results .

The `MissingNumber` program calculates the expected sum of the first n natural numbers using the formula n(n+1)/2, where n is the length of the array plus one because one number is missing. It iterates through the array, subtracting each element from this expected sum. The remaining value in the sum variable after the loop completes is the missing number. This method is efficient, operating in O(n) time complexity .

The `BubbleSort` algorithm sorts the array by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. This process is repeated for each element until no more swaps are needed, indicating that the array is sorted. A major drawback of Bubble Sort is its time complexity of O(n^2), making it inefficient on large lists compared to more advanced algorithms such as QuickSort or MergeSort, which operate in O(n log n).

The `AnagramCheck` program checks if two strings are anagrams by converting both strings to character arrays, sorting these arrays, and then comparing them for equality. When the sorted arrays match, the strings are anagrams. Sorting both strings gives the program a time complexity of O(n log n) due to the sorting operation, where n is the length of the strings. The approach efficiently verifies anagram status but has added cost from sorting compared to a more optimal method using frequency counting .

The `PasswordValidation` program checks password validity using several criteria: the password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character from the set [@#$%^&+=]. These conditions are checked using regular expressions combined with logical AND operations. If all conditions are met, the password is considered valid. This approach ensures basic standards for password strength and complexity .

The `PrimeNumbers` program checks each number in the array using the `isPrime` method, which determines if a number is prime by checking divisibility from 2 up to the square root of the number. If divisible by any of these, it's not prime. If a number is prime, it's added to the sum, and the count is incremented. The program then prints all primes, their sum, and the count .

The `SecondLargest` program sorts the entire array in ascending order using `Arrays.sort()` and then directly accesses the second last element as the second largest element. This approach is inefficient for large datasets because it sorts the whole array, which has a time complexity of O(n log n), whereas finding the second largest element can be done more efficiently in O(n) time by a single pass through the array to track the two largest elements .

The 'Longest Increasing Subsequence' (LIS) algorithm uses dynamic programming to find the length of the longest subsequence where elements are in increasing order. It initializes an array `lis` where each element is initially set to 1, representing the minimum possible length. It iteratively updates `lis[i]` for each element such that for every j < i, if arr[i] > arr[j], `lis[i]` could be `lis[j] + 1` if it leads to a longer subsequence. After iterating, the maximum value in the lis array is the length of the LIS. This approach has a time complexity of O(n^2) due to the nested iteration .

You might also like