[Go to site: main page, start]

0% found this document useful (0 votes)
13 views12 pages

Java Array and String Operations Guide

The document contains multiple Java programs demonstrating various array and string manipulations, including copying arrays, finding frequencies, identifying duplicates, and reversing arrays. It also includes string operations such as counting characters, vowels, and consonants, removing whitespace, and finding duplicate words. Each program is accompanied by its output to illustrate the results of the operations performed.
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)
13 views12 pages

Java Array and String Operations Guide

The document contains multiple Java programs demonstrating various array and string manipulations, including copying arrays, finding frequencies, identifying duplicates, and reversing arrays. It also includes string operations such as counting characters, vowels, and consonants, removing whitespace, and finding duplicate words. Each program is accompanied by its output to illustrate the results of the operations performed.
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

Program to copy all elements of one array into another array

public class CopyArray {


public static void main(String[] args) {
//Initialize array
int [] arr1 = new int [] {1, 2, 3, 4, 5};
//Create another array arr2 with size of arr1
int arr2[] = new int[[Link]];
//Copying all elements of one array into another
for (int i = 0; i < [Link]; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
[Link]("Elements of original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr1[i] + " ");
}

[Link]();

//Displaying elements of array arr2


[Link]("Elements of new array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr2[i] + " ");
}
}
}
Output:

Elements of original array


12345
Elements of new array:
12345

Program to find the frequency of each element in the array


public class Frequency {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
//Array fr will store frequencies of element
int [] fr = new int [[Link]];
int visited = -1;
for(int i = 0; i < [Link]; i++){
int count = 1;
for(int j = i+1; j < [Link]; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}

//Displays the frequency of each element present in array


[Link]("---------------------------------------");
[Link](" Element | Frequency");
[Link]("---------------------------------------");
for(int i = 0; i < [Link]; i++){
if(fr[i] != visited)
[Link](" " + arr[i] + " | " + fr[i]);
}
[Link]("----------------------------------------");
}}
Output:

----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------

Program to print the duplicate elements of an array


public class DuplicateElement {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
[Link]("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < [Link]; i++) {
for(int j = i + 1; j < [Link]; j++) {
if(arr[i] == arr[j])
[Link](arr[j]);
}
}
}
}
Output:

Duplicate elements in given array:


2
3
8

Program to print the elements of an array in reverse order


public class ReverseArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
[Link]("Original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
[Link]();
[Link]("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = [Link]-1; i >= 0; i--) {
[Link](arr[i] + " ");
}
}
}
Output:

Original array:
1 2 3 4 5
Array in reverse order:
5 4 3 2 1

Program to print the elements of an array present on even


position
public class EvenPosition {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};

[Link]("Elements of given array present on even position: ");


//Loop through the array by incrementing value of i by 2
//Here, i will start from 1 as first even positioned element is present at position 1.
for (int i = 1; i < [Link]; i = i+2) {
[Link](arr[i]);
}
}
}
Output:

Elements of given array present on even position:


2
4

Program to print the elements of an array present on odd


position
public class OddPosition {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
[Link]("Elements of given array present on odd position: ");
//Loop through the array by incrementing value of i by 2
for (int i = 0; i < [Link]; i = i+2) {
[Link](arr[i]);
}
}
}
Output:

Elements of given array present on odd position:


1
3
5
Program to print the largest element in an array
public class LargestElement_array {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < [Link]; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
[Link]("Largest element present in given array: " + max);
}
}
Output:

Largest element present in given array: 75

Program to print the smallest element in an array


public class SmallestElement_array {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize min with first element of array.
int min = arr[0];
//Loop through the array
for (int i = 0; i < [Link]; i++) {
//Compare elements of array with min
if(arr[i] <min)
min = arr[i];
}
[Link]("Smallest element present in given array: " + min);
}
}
Output:

Smallest element present in given array: 7


Java Program to print the sum of all the items of the array
public class SumOfArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
//Loop through the array to calculate sum of elements
for (int i = 0; i < [Link]; i++) {
sum = sum + arr[i];
}
[Link]("Sum of all the elements of an array: " + sum);
}
}
Output:

Sum of all the elements of an array: 15

Java String Programs

Java Program to count the total number of characters in a string

public class CountCharacter


{
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;

//Counts each character except space


for(int i = 0; i < [Link](); i++) {
if([Link](i) != ' ')
count++;
}

//Displays the total number of characters present in the given string


[Link]("Total number of characters in a string: " + count);
}
}
Output:

Total number of characters in a string: 19


Java Program to count the total number of vowels and consonants in a string

public class CountVowelConsonant {


public static void main(String[] args) {

//Counter variable to store the count of vowels and consonant


int vCount = 0, cCount = 0;

//Declare a string
String str = "This is a really simple sentence";

//Converting entire string to lower case to reduce the comparisons


str = [Link]();

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


//Checks whether a character is a vowel
if([Link](i) == 'a' || [Link](i) == 'e' || [Link](i) == 'i' || [Link](i) == 'o'
|| [Link](i) == 'u') {
//Increments the vowel counter
vCount++;
}
//Checks whether a character is a consonant
else if([Link](i) >= 'a' && [Link](i)<='z') {
//Increments the consonant counter
cCount++;
}
}
[Link]("Number of vowels: " + vCount);
[Link]("Number of consonants: " + cCount);
}
}
Output:

Number of vowels: 10
Number of consonants: 17

Java Program to remove all the white spaces from a string


public class removeWhiteSpace {
public static void main(String[] args) {

String str1="Remove white spaces";

//Removes the white spaces using regex


str1 = [Link]("\\s+", "");

[Link]("String after removing all the white spaces : " + str1);


}
}
Output:

String after removing all the white spaces: Removewhitespaces

Java Program to replace lower-case characters with upper-case and


vice-versa
public class changeCase {
public static void main(String[] args) {

String str1="Great Power";


StringBuffer newStr=new StringBuffer(str1);

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

//Checks for lower case character


if([Link]([Link](i))) {
//Convert it into upper case using toUpperCase() function
[Link](i, [Link]([Link](i)));
}
//Checks for upper case character
else if([Link]([Link](i))) {
//Convert it into upper case using toLowerCase() function
[Link](i, [Link]([Link](i)));
}
}
[Link]("String after case conversion : " + newStr);
}
}
Output:

String after case conversion: gREAT pOWER

Java Program to replace the spaces of a string with a specific


character
public class ReplaceSpace
{
public static void main(String[] args) {
String string = "Once in a blue moon";
char ch = '-';

//Replace space with specific character ch


string = [Link](' ', ch);

[Link]("String after replacing spaces with given character: ");


[Link](string);
}
}
Output:

String after replacing spaces with given character:


Once-in-a-blue-moon

Java program to find the duplicate words in a string


public class DuplicateWord {
public static void main(String[] args) {
String string = "Big black bug bit a big black dog on his big black nose";
int count;

//Converts the string into lowercase


string = [Link]();

//Split the string into words using built-in function


String words[] = [Link](" ");

[Link]("Duplicate words in a given string : ");


for(int i = 0; i < [Link]; i++) {
count = 1;
for(int j = i+1; j < [Link]; j++) {
if(words[i].equals(words[j])) {
count++;
//Set words[j] to 0 to avoid printing visited word
words[j] = "0";
}
}

//Displays the duplicate word if count is greater than 1


if(count > 1 && words[i] != "0")
[Link](words[i]);
}
}
}
Output:

Duplicate words in a given string :


big
black

Java Program to find the frequency of characters


public class FrequencyCharacter
{
public static void main(String[] args) {
String str = "picture perfect";
int[] freq = new int[[Link]()];
int i, j;

//Converts given string into character array


char string[] = [Link]();

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


freq[i] = 1;
for(j = i+1; j <[Link](); j++) {
if(string[i] == string[j]) {
freq[i]++;

//Set string[j] to 0 to avoid printing visited character


string[j] = '0';
}
}
}

//Displays the each character and their corresponding frequency


[Link]("Characters and their corresponding frequencies");
for(i = 0; i <[Link]; i++) {
if(string[i] != ' ' && string[i] != '0')
[Link](string[i] + "-" + freq[i]);
}
}
}
Output:

Characters and their corresponding frequencies


p-2
i-1
c-2
t-2
u-1
r-2
e-3
f-1

Java Program to find the largest and smallest word in a string.


public class SmallestLargestWord

public static void main(String[] args){


String string = "Hardships often prepare ordinary people for an extraordinary destiny";
String word = "", small = "", large="";
String[] words = new String[100];
int length = 0;

//Add extra space after string to get the last word in the given string
string = string + " ";

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


//Split the string into words
if([Link](i) != ' '){
word = word + [Link](i);
}
else{
//Add word to array words
words[length] = word;
//Increment length
length++;
//Make word an empty string
word = "";
}
}
//Initialize small and large with first word in the string
small = large = words[0];

//Determine smallest and largest word in the string


for(int k = 0; k < length; k++){

//If length of small is greater than any word present in the string
//Store value of word into small
if([Link]() > words[k].length())
small = words[k];

//If length of large is less than any word present in the string
//Store value of word into large
if([Link]() < words[k].length())
large = words[k];
}
[Link]("Smallest word: " + small);
[Link]("Largest word: " + large);
} }
Output:

Smallest word: an
Largest word: extraordinar

Common questions

Powered by AI

The algorithm initializes a variable to hold the maximum value with the value of the first element. It then iterates through the array, updating this variable whenever a larger element is encountered, ensuring it always holds the highest value found .

To print elements in reverse order, the program iterates over the array backwards, starting from the last index, continuing to the first index, thus reversing the output order by leveraging the sequential index decrement approach .

The method employs a regular expression to remove all whitespace by replacing them with an empty string. This efficiently condenses the string but cannot differentiate between intended spaces for formatting or mistakes, potentially impacting readability if not carefully implemented .

Counting vowels and consonants requires differentiating between character types using conditional checks within the iteration logic (i.e., checking if they are among certain characters for vowels and alphabetic but not vowels for consonants), whereas counting total characters aggregates every encounter except spaces .

The program checks each character to determine if it's lowercase or uppercase, using helper functions to convert it to the opposite case. Challenges include managing non-alphabetic characters, consistently implementing locale-specific case rules, and handling multibyte characters in Unicode .

To copy elements from one array to another in Java, a new array of the same length as the original array is created. Then, a loop iterates through each index of the original array, assigning the value at each index to the same index in the new array .

The program iterates over the array, starting from the second element (index 1), and increments by 2 in each iteration. This method effectively isolates even-positioned elements as per 1-based indexing .

Calculating the frequency requires maintaining a count for each element and ensuring that each element is not double-counted. This involves using an auxiliary array to track the 'visited' status of elements, which adds complexity beyond simply identifying duplicates where elements are printed upon detection without such secondary structures .

Using a 'visited' flag prevents elements or characters from being counted multiple times. When an element's frequency is determined, the flag marks it as 'visited,' ensuring subsequent iterations do not recount it, thus eliminating redundant computations and ensuring accuracy .

The program identifies duplicate elements by comparing each element with the subsequent elements in the array. If a duplicate is found, it is printed, ensuring each element is compared only once to avoid redundant outputs .

You might also like