0% found this document useful (0 votes)
5 views2 pages

Java Code Examples for Common Tasks

The document contains four program code snippets. The first finds the longest word in a given text, the second removes specified elements from an array, the third checks if a number is prime and calculates the sum of prime numbers in a range, and the fourth defines a class to print even numbers in a specified range using threading. Each code snippet demonstrates different programming concepts and functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Code Examples for Common Tasks

The document contains four program code snippets. The first finds the longest word in a given text, the second removes specified elements from an array, the third checks if a number is prime and calculates the sum of prime numbers in a range, and the fourth defines a class to print even numbers in a specified range using threading. Each code snippet demonstrates different programming concepts and functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

//Program code 1

public static String findLongestWord(String text) {


String longestWord = "";

// Split the text into words based on whitespace


String[] words = [Link]("\\s+");

// Iterate through each word to find the longest one


for (String word : words) {
if ([Link]() > [Link]()) {
longestWord = word;
}
}
return longestWord;
}

//program code 2
public static int[] removeAll(int[] array, int elementToRemove) {
int[] result = new int[[Link]];
int index = 0;

// Iterate through the original array


for (int value : array) {
// Copy only if the current element is not equal to the element to be removed
if (value != elementToRemove) {
result[index++] = value;
}
}

// If the resulting array is smaller than the original, resize it


return [Link](result, index);
}

//program code 3
public static boolean isPrime(int n) {

if (n <= 1) {

return false;

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

if (n % i == 0) {

return false;

}
}

return true;

// Function to compute sum of all prime numbers in range x to y

public static int primeSum(int x, int y) {

int sum = 0;

for (int i = x; i <= y; i++) {

if (isPrime(i)) {

sum += i;

return sum;

//program code 4
private int start;
private int end;

// Constructor to initialize start and end


public PrintNumbers(int start, int end) {
[Link] = start;
[Link] = end;
}

@Override
public void run() {
for (int i = start; i <= end; i += 2) {
[Link]([Link]().getName() + ": " + i);
}
}

You might also like