instruction stringlengths 38 3.13k | output stringlengths 288 7.87k | __index_level_0__ int64 34 58.2k |
|---|---|---|
Create a program in Java to print out the Fibonacci sequence of numbers up to a given limit, where the limit is an input provided by the user. | Sure! Here's an example program in Java that prompts the user to enter a limit and then prints out the Fibonacci sequence up to that limit:
```java
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.... | 19,667 |
Write a code to implement Selection Sort in Java with the following additional constraints and requirements:
- The code must be implemented using recursion instead of iteration.
- The input array must contain at least 10 elements.
- The code must be written using object-oriented programming principles.
- The code shoul... | Here's an example code that implements Selection Sort recursively in Java:
```java
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {5, 3, 7, 2, 8, 1, 6, 4, 9, 0};
selectionSort(arr, 0);
System.out.println("Sorted array:");
for (int num : ar... | 19,684 |
Create an array in Java with 1,000,000 floating-point values and output the average of these values. | Here's a Java code snippet that creates an array with 1,000,000 floating-point values and calculates their average:
```java
import java.util.Random;
public class FloatingPointArray {
public static void main(String[] args) {
// Create the array
float[] floatArray = new float[1000000];
// G... | 19,699 |
Create a method to print all the prime numbers up to n, but the method should be written using a recursive approach instead of an iterative approach. | Here's a recursive method in Java to print all the prime numbers up to n:
```java
public class PrimeNumbersRecursive {
public static void printPrimes(int n) {
printPrimesHelper(n, 2);
}
private static void printPrimesHelper(int n, int num) {
if (num <= n) {
if (isPrime(num)) {... | 19,805 |
Create a Java class that prints the Fibonacci sequence between 0 and 10, but only display the even numbers in the sequence. | Here is a Java class that prints the Fibonacci sequence between 0 and 10, but only displays the even numbers in the sequence:
```java
public class FibonacciEven {
public static void main(String[] args) {
int n = 10; // Limit for the Fibonacci sequence
int[] fibonacci = new int[n + 1]; // Array to s... | 19,848 |
Create an integer array using Java and sort it using the bubble sort algorithm. Additionally, add a condition to the sorting algorithm that allows for sorting the array in descending order instead of ascending order. | Sure! Here's an example of how you can create an integer array in Java and sort it using the bubble sort algorithm. I have also added a condition to allow for sorting the array in descending order.
```java
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] ar... | 19,868 |
Create a class in Java that can store a list of students, their courses, and their corresponding grades. Additionally, implement methods to calculate the average grade for each student and for each course. | Here is an example of how you can create a class in Java to store a list of students, their courses, and their corresponding grades. It also includes methods to calculate the average grade for each student and for each course.
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import ... | 19,966 |
Write a Java Method that takes an array of integers and returns true if the array is sorted in ascending order and does not contain any duplicate values.
array = [7, 18, 24, 55, 98] | Here's the Java method that takes an array of integers and returns true if the array is sorted in ascending order and does not contain any duplicate values:
```java
public static boolean isSortedAndNoDuplicates(int[] arr) {
// Check if array is empty or has only one element
if (arr.length < 2) {
return... | 19,983 |
Write a method that prints out a square of size n. Each element in the square should be the sum of its row and column indices.
For example, if n=5, the output should be:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8 | Here is an example implementation in Java:
```java
public static void printSquare(int n) {
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.print(row + col + " ");
}
System.out.println();
}
}
```
To use this method and print a square of siz... | 19,984 |
Write a method that prints out all the prime numbers between 1 and 1,000,000. | Here's an example of a method that prints out all the prime numbers between 1 and 1,000,000 using the Sieve of Eratosthenes algorithm:
```java
public static void printPrimes() {
boolean[] isPrime = new boolean[1000001];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false; // 0 and 1 are not pr... | 19,988 |
Write a Java method that takes a string and prints out the number of occurrences of each unique vowel in the string. Ignore case sensitivity.
String = "adda123de3f" | Here's an example Java method that takes a string and prints out the number of occurrences of each unique vowel in the string, ignoring case sensitivity:
```java
public static void countVowels(String str) {
str = str.toLowerCase(); // Convert the string to lowercase to ignore case sensitivity
int[] vowelsCount... | 19,993 |
Implement a custom ArrayList class in Java without using any built-in data structures or collections libraries. The custom ArrayList should have the following methods:
- add(element): adds the specified element to the end of the list
- remove(index): removes the element at the specified index from the list
- get(index)... | Here's an implementation of a custom ArrayList class in Java:
```java
public class CustomArrayList<T> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] elements;
private int size;
public CustomArrayList() {
this.elements = new Object[DEFAULT_CAPACITY];
this.size = 0;
... | 19,994 |
Implement an algorithm to reverse a string in Java without using any built-in string manipulation methods or additional data structures. The algorithm should have a time complexity of O(n) and a space complexity of O(1). | Here is the Java implementation of the algorithm to reverse a string without using any built-in string manipulation methods or additional data structures:
```java
public class ReverseString {
public static void main(String[] args) {
String str = "Hello, World!";
String reversed = reverseString(str)... | 19,997 |
Construct an if-else statement in Java for printing the square root of a given number only if the number is positive and less than or equal to 100. | Here's an example of an if-else statement in Java that prints the square root of a given number only if the number is positive and less than or equal to 100:
```java
import java.util.Scanner;
public class SquareRootChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in)... | 20,083 |
Implement the following algorithm in Java, with a slight modification to the original bubble sort algorithm.
// Modified Bubble sort algorithm
for i in 1 to n-1
for j in 0 to n-i-1
if array[j] > array[j+1]
swap array[j] and array[j+1] | Here's the implementation of the modified bubble sort algorithm in Java:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 3, 8, 2, 1};
int n = array.length;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
... | 20,112 |
Write a code in Java to replace all the occurrences of a given value (5) in an array with a new value (10). If the given value is not found in the array, the code should print an error message "Value not found".
arr = [2, 5, 1, 5, 8]
#Additional Requirements#
1. The code should handle both primitive integer arrays an... | Here is the code that meets the given requirements:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReplaceValue {
public static void main(String[] args) {
int[] arr1 = {2, 5, 1, 5, 8};
replaceValue(arr1, 5, 10);
System.out.println(Arra... | 20,209 |
Write a Java program that creates a GUI window with a button. When the button is clicked, display a message box with a customized message. | Here's an example of a Java program that creates a GUI window with a button and displays a message box with a customized message when the button is clicked:
```java
import javax.swing.*;
import java.awt.event.*;
public class CustomMessageBoxExample {
public static void main(String[] args) {
JFrame frame =... | 20,251 |
Generate a for loop in Java to display all the odd numbers between 1 and 10, but skip the number 5. | Here is the for loop in Java to display all the odd numbers between 1 and 10, but skip the number 5:
```java
for (int i = 1; i <= 10; i += 2) {
if (i == 5) {
continue;
}
System.out.println(i);
}
```
In this loop, the variable `i` starts at 1 and is incremented by 2 in each iteration to only consid... | 20,311 |
Write a Java program to sort a list of strings alphabetically, but with the following additional requirement:
- The program should ignore any special characters or punctuation marks in the strings while sorting.
- The program should handle strings with different letter cases (uppercase and lowercase) and sort them acc... | Here is a Java program that sorts a list of strings alphabetically while ignoring special characters and handling different letter cases:
```java
import java.text.Collator;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public... | 20,312 |
Implement an Insertion Sort algorithm in Java.
Reference code:
```
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
insertionSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void in... | The error in the reference code is the initialization of the variable `j` in the `insertionSort` method. It should be initialized with `i` instead of `i - 1`. Here is the corrected code:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
inser... | 20,340 |
Write a code snippet to delete all elements from a doubly linked list, ensuring that the deletion process takes constant time complexity. | To delete all elements from a doubly linked list with constant time complexity, we can update the head and tail pointers of the list to null. This will effectively detach all elements from the list, making them eligible for garbage collection.
Here's an example implementation in Java:
```java
class Node {
int dat... | 20,361 |
Write a Java program to read a given string and print out the characters of the string in reverse order. | Sure! Here's a Java program that reads a given string and prints out the characters of the string in reverse order:
```java
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
// Read the input string
Scanner scanner = new Scanner(System.in);
Sys... | 20,397 |
Write a Java program to generate a random number between 25 and 75, but ensure that the generated number is divisible by 5. | Here is a Java program that generates a random number between 25 and 75, but ensures that the generated number is divisible by 5:
```java
import java.util.Random;
public class RandomNumberDivisibleBy5 {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = rando... | 20,447 |
Create a program in Java that validates an input string for containing only numbers. The program should also check if the input string is not empty and has a maximum length of 10 characters. | Here's a Java program that validates an input string for containing only numbers, checking if it's not empty and has a maximum length of 10 characters:
```java
import java.util.Scanner;
public class NumberValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
... | 20,459 |
Create a class in Java to represent a circle with two fields for its radius and color. The radius should be a positive integer and the color should be a string of maximum length 20 characters. Additionally, the class should have methods to calculate and return the circumference and area of the circle, as well as a meth... | Here's the implementation of the Circle class in Java:
```java
public class Circle {
private int radius;
private String color;
// Constructor
public Circle(int radius, String color) {
this.radius = radius;
this.color = color;
}
// Getter methods
public int getRadius() {
... | 20,517 |
Implement a thread pool in Java that supports dynamic resizing of the pool based on the current workload. Additionally, the thread pool should have a scheduling mechanism that prioritizes tasks based on their urgency and assigns them to threads accordingly. | Here's an example of implementing a thread pool in Java that supports dynamic resizing and task scheduling based on urgency:
```java
import java.util.Comparator;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class DynamicThreadPool {
private final int corePoolSize;
pr... | 20,548 |
Write a Java method to check if a numerical value is within a specified range and return the number of times the value appears in the range.
Signature:
```java
public static int countValuesInRange(int[] nums, int startRange, int endRange)
```
Input:
- An array of integers `nums` (1 <= nums.length <= 10^6) where each ... | Here's the implementation of the `countValuesInRange` method in Java:
```java
public static int countValuesInRange(int[] nums, int startRange, int endRange) {
int count = 0;
for (int num : nums) {
if (num >= startRange && num <= endRange) {
count++;
}
}
return count;
}
```... | 20,584 |
Create a for loop in Java using the given array and print out only the even numbers in the array. | Here's an example of how you can create a for loop in Java to print out only the even numbers in an array:
```java
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2... | 20,613 |
Create an algorithm in Java to sort an array in descending order using a specific sorting algorithm called "QuickSort".
array = [10, 15, 7, 2, 13, 18] | Here is an implementation of the QuickSort algorithm in Java to sort the given array in descending order:
```java
public class QuickSortDescending {
public static void main(String[] args) {
int[] array = {10, 15, 7, 2, 13, 18};
quickSortDescending(array, 0, array.length - 1);
... | 20,812 |
Write a Java program to find the maximum and minimum values in an array of integers, excluding any duplicates.
#Additional Notes#
- The array can contain both positive and negative numbers.
- The array may have a variable number of elements, ranging from 1 to 1000.
- The program should return both the maximum and mini... | Here is a Java program that finds the maximum and minimum values in an array of integers, excluding any duplicates:
```java
import java.util.Arrays;
public class FindMinMax {
public static void main(String[] args) {
int[] array = {10, 5, 2, 10, 3, -5, -10, 2, 5};
// Sort the array in ascending or... | 20,888 |
Create a Java program to convert a 2D array of integers into a single integer. The 2D array represents a matrix, where each element in the array represents a digit. The resulting integer should be obtained by reading the digits row by row, from left to right. The input array is guaranteed to have at least one row and o... | Here's a Java program that converts a 2D array of integers into a single integer:
```java
public class ArrayToIntegerConverter {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int result = convert... | 21,013 |
Create a Java program to find the maximum element of an array that also meets the following criteria:
1. The maximum element must be odd.
2. The maximum element must be a prime number.
3. The program must not use any built-in Java libraries or methods for finding prime numbers.
arr = [2, 3, 1, 4, 5] | Here's a Java program that finds the maximum element of an array that is both odd and a prime number:
```java
public class Main {
public static void main(String[] args) {
int[] arr = {2, 3, 1, 4, 5};
int maxOddPrime = findMaxOddPrime(arr);
System.out.println("Maximum odd prime number in th... | 21,110 |
Write a method which takes 2 parameters, both of which are positive integers, and returns the greater one. The method should also handle the case where one or both of the parameters are negative numbers, in which case it should return an error message indicating that negative numbers are not allowed. Additionally, the ... | Here's an implementation of the method in Java:
```java
public static String getGreaterNumber(int num1, int num2) {
if (num1 < 0 || num2 < 0) {
return "Negative numbers are not allowed.";
} else if (num1 < 1 || num1 > 1000 || num2 < 1 || num2 > 1000) {
return "Parameters are out of range.";
... | 21,188 |
Write a Java program to convert a binary string to a decimal number. The binary string can have a maximum length of 32 characters. Additionally, the program should handle cases where the binary string contains leading or trailing whitespace characters. | Here is a Java program that converts a binary string to a decimal number while handling leading and trailing whitespace characters:
```java
public class BinaryToDecimal {
public static void main(String[] args) {
String binaryString = " 1010110 "; // example binary string with leading and trailing whitespac... | 21,256 |
Write a Java method that takes a string and returns a copy of the string with all lowercase letters replaced with uppercase letters and vice versa. The method should also remove any spaces in the string and return the modified string. | Here's a Java method that takes a string, replaces lowercase letters with uppercase letters and vice versa, and removes any spaces in the string:
```java
public class StringModifier {
public static String modifyString(String input) {
String modifiedString = "";
for (int i = 0; i < input.length(); i... | 21,265 |
Write a Java program to add two large numbers of any length, but without using the `+` operator or any built-in libraries for addition. | Here's a Java program that adds two large numbers of any length without using the `+` operator or any built-in libraries for addition:
```java
import java.util.Scanner;
public class AddLargeNumbers {
public static String add(String num1, String num2) {
StringBuilder result = new StringBuilder();
... | 21,266 |
Create an array of strings in Java that only contains words starting with a vowel and have a length of more than 5 characters. | Here is an example of how you can create an array of strings in Java that only contains words starting with a vowel and have a length of more than 5 characters:
```java
public class Main {
public static void main(String[] args) {
String[] words = {"apple", "banana", "orange", "elephant", "igloo", "umbrella... | 21,338 |
Write a Java class called "Car" that has the following properties:
1. A private integer variable called "year" that represents the manufacturing year of the car.
2. A private string variable called "make" that represents the brand or make of the car.
3. A private string variable called "model" that represents the mode... | Here is the implementation of the Car class:
```java
public class Car {
private int year;
private String make;
private String model;
public Car() {
this.year = 0;
this.make = "";
this.model = "";
}
public Car(int year, String make, String model) {
this.year = y... | 21,387 |
Create a Java method to print a two-dimensional array in a spiral order. The array will always have an odd number of rows and columns. The method should start printing from the top left element and move in a clockwise direction. | Here is a Java method that prints a two-dimensional array in a spiral order:
```java
public class SpiralOrder {
public static void printSpiral(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int top = 0, bottom = rows - 1, left = 0, right = columns - 1;
... | 21,560 |
Generate a Java code to display the multiplication table from 1 to 20, including both rows and columns.
#Additional Instructions#
1. Use nested loops to generate the multiplication table.
2. Format the output in a tabular format, with appropriate spacing between numbers.
3. Include a header row and column to label the... | Here is the Java code to display the multiplication table from 1 to 20:
```java
public class MultiplicationTable {
public static void main(String[] args) {
int tableSize = 20;
displayMultiplicationTable(tableSize);
}
public static void displayMultiplicationTable(int size) {
// ... | 21,574 |
Create a loop in Java for printing all elements of an array of strings in reverse order.
["String4", "String3", "String2", "String1"] | Sure! Here's an example of a loop in Java that prints all elements of an array of strings in reverse order:
```java
public class Main {
public static void main(String[] args) {
String[] arr = {"String4", "String3", "String2", "String1"};
for (int i = arr.length - 1; i >= 0; i--) {
... | 21,575 |
Write a code in Java to find the factorial of a number using recursion. | Here's a Java code to find the factorial of a number using recursion:
```java
public class FactorialRecursion {
public static int factorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
public static void main... | 21,581 |
Generate a random alphanumeric string of length n in Java, where n is an input provided by the user. The generated string should include at least one uppercase letter, one lowercase letter, one digit, and one special character. The time complexity of the solution should be O(n), and the space complexity should be O(1). | Here's a Java code that generates a random alphanumeric string of length n, meeting all the given requirements:
```java
import java.util.Random;
public class RandomStringGenerator {
public static void main(String[] args) {
int n = getInputFromUser();
String randomString = generateRandomString(n);
... | 21,599 |
Create a Java object for a student with the fields 'Name', 'Marks', and 'Attendance'. The 'Attendance' field should be a list of integers representing the student's attendance record for each class. The 'Marks' field should be a map where the key is the subject name (String) and the value is a list of integers represen... | Here's a Java class that represents a student with the given fields and methods:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Student {
private String name;
private Map<String, List<Integer>> marks;
private List<Integer> attendance... | 21,646 |
Create a method to read in input from the console in Java, with the additional requirement that the method should be able to handle different types of input (such as integers, floating-point numbers, and strings) and validate the input according to certain criteria.
For example, the method should be able to handle the... | Here is an example of a method that reads input from the console, handles different types of input, and validates the input according to certain criteria:
```java
import java.util.Scanner;
public class InputReader {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String... | 21,771 |
Create a Java program to generate and print the Fibonacci series up to a given size. The program should prompt the user to enter the desired size of the series and then generate the Fibonacci series based on the input.
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones... | Here is a Java program that generates and prints the Fibonacci series up to a given size, based on user input:
```java
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the desire... | 21,850 |
Create a class in Java to store student information such as name, age, course, and grade point average. Implement a method that calculates the student's cumulative GPA by taking into account the credits earned for each course. The GPA should be rounded to two decimal places. Additionally, include a method that returns ... | Here is an example implementation of the class in Java:
```java
import java.text.DecimalFormat;
public class Student {
private String name;
private int age;
private String course;
private double cumulativeGPA;
public Student(String name, int age, String course) {
this.name = name;
... | 21,855 |
Create a Java program to print a square diamond pattern with '*' characters. However, the program should also include a method to check if a given number is prime and only print the diamond pattern if the input number is prime. | Sure! Here's a Java program that prints a square diamond pattern with '*' characters, and includes a method to check if a given number is prime. The program only prints the diamond pattern if the input number is prime.
```java
import java.util.Scanner;
public class SquareDiamondPattern {
public static void main(... | 22,024 |
Generate a Java program that prints the longest word in a sentence, considering that the sentence may contain multiple words with the same length. If there are multiple longest words, the program should print all of them. | Here is a Java program that prints the longest word(s) in a sentence:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LongestWordFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a ... | 22,095 |
Create a for loop in Java to find the sum of the first 20 prime numbers. | Here's an example of a for loop in Java to find the sum of the first 20 prime numbers:
```java
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 2; count < 20; i++) {
if (isPrime(i)) {
sum += i;... | 22,098 |
Write a Java method to insert a given string at the beginning of every word in a given sentence. The given sentence can contain special characters, numbers, and multiple consecutive spaces between words. The inserted string should be enclosed in square brackets.
Example:
Input:
String sentence = "The quick brown fo... | Here is a Java method that inserts a given string at the beginning of every word in a given sentence:
```java
public class Main {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog 12345";
String insertedString = "Hello";
String result... | 22,134 |
Write a Java method that takes an array of integers as input and returns the sum of all the even numbers in the array. | Here is a Java method that takes an array of integers as input and returns the sum of all the even numbers in the array:
```java
public class SumOfEvenNumbers {
public static int sumOfEvenNumbers(int[] numbers) {
int sum = 0;
for (int number : numbers) {
if (number % 2 == ... | 22,231 |
Write a Java method that takes two numbers and returns the sum of their digits. | Here's a Java method that takes two numbers and returns the sum of their digits:
```java
public static int sumOfDigits(int num1, int num2) {
int sum = 0;
// Calculate the sum of digits for num1
while (num1 != 0) {
int digit = num1 % 10;
sum += digit;
num1 /= 10;
}
// Calcu... | 22,233 |
Write Java code for converting a string to an array, but exclude any vowels from the resulting array.
String: "Hello"
# Erroneous Code #
Write Java code for converting a string to an array, but include only vowels in the resulting array.
String: "Hello" | Here is the Java code to convert a string to an array while excluding any vowels from the resulting array:
```java
public class StringToArrayWithoutVowels {
public static void main(String[] args) {
String str = "Hello";
char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
ch... | 22,324 |
Write a Java program to create a thread which prints the numbers from 10 to 0 in reverse order after every 1 second. Additionally, the program should display a message "Thread is interrupted" if the thread is interrupted before completing its task. | Here is the Java program that creates a thread to print numbers from 10 to 0 in reverse order after every 1 second:
```java
public class ReverseNumberThread extends Thread {
@Override
public void run() {
try {
for (int i = 10; i >= 0; i--) {
System.out.println(i);
... | 22,326 |
Write a Java program to compare two strings lexicographically and return the index of the first different character.
Two strings: string1="GeeksforGeeks" and string2="GeeksGforGeks"
#Erroneous Code#
Write a Java program to compare two strings lexicographically. Two strings: string1="GeeksforGeeks" and string2="GeeksQu... | Here is the correct code:
```java
public class StringComparison {
public static void main(String[] args) {
String string1 = "GeeksforGeeks";
String string2 = "GeeksGforGeks";
int index = compareStrings(string1, string2);
System.out.println("First different characte... | 22,346 |
Implement a password validator in Java that meets the following requirements:
- The password must contain at least one uppercase letter.
- The password must contain at least one lowercase letter.
- The password must contain at least one digit.
- The password must contain at least one special character (!, @, #, $, %, ^... | Here is one way to implement a password validator in Java:
```java
import java.util.regex.Pattern;
public class PasswordValidator {
private static final String SPECIAL_CHARACTERS = "!@#$%^&*()-_+={}[]|\\:;\"'<>,.?/`";
public static boolean validatePassword(String password) {
if (password.contains(" "... | 22,383 |
Write a code in Java to find all the prime numbers between 0 and n, where n can be as large as 10^9. Additionally, the code should be optimized to run within a time complexity of O(nlog(logn)). | Here is the code in Java to find all the prime numbers between 0 and n, optimized to run within a time complexity of O(nlog(logn)):
```java
import java.util.ArrayList;
public class PrimeNumbers {
public static ArrayList<Integer> sieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n+1];
f... | 22,393 |
Create an array in Java that contains five elements each of type String. Additionally, ensure that each element in the array is unique. | Here is an example of how you can create an array in Java that contains five elements, each of type String, with each element being unique:
```java
public class Main {
public static void main(String[] args) {
String[] array = new String[5];
array[0] = "Element 1";
array[1] = "Eleme... | 22,461 |
Write a Java program that asks the user to input a character and then performs the following operations on it:
1. Check if the character is a letter (either uppercase or lowercase).
2. If it is a letter, determine if it is a vowel or a consonant.
3. If it is a vowel, display a message saying "The entered character is a... | Here is the Java program that performs the operations as described:
```java
import java.util.Scanner;
public class CharacterCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a character: ");
String input = scanner.n... | 22,529 |
Create a Java program that takes three numbers and prints out the largest number.
Number 1: 6
Number 2: 8
Number 3: 10 | Here is a Java program that takes three numbers and prints out the largest number:
```java
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number 1: ");
int num1 = scanner.nextInt()... | 22,549 |
Write a recursive implementation of the Binary Search algorithm in Java. | Here is a recursive implementation of the Binary Search algorithm in Java:
```java
public class BinarySearch {
public static int binarySearch(int[] array, int target) {
return binarySearch(array, target, 0, array.length - 1);
}
private static int binarySearch(int[] array, int target, int low, int... | 22,572 |
Write a JAVA program to display the list of prime numbers from 1 to 100. | Here's a Java program that displays the list of prime numbers from 1 to 100:
```java
public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 100 are:");
for (int i = 2; i <= 100; i++) {
if (isPrime(i)) {
System... | 22,586 |
Write a Java code to perform binary search on the given sorted array. | Here is an example Java code to perform binary search on a given sorted array:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
... | 22,598 |
Write an Android application that displays the current date and time in a text view and allows the user to toggle between 12-hour and 24-hour time formats. | To create an Android application that displays the current date and time in a text view and allows the user to toggle between 12-hour and 24-hour time formats, you can follow these steps:
Step 1: Set up the project
- Open Android Studio and create a new project.
- Choose an appropriate project name, package name, and ... | 22,603 |
Create a class in Java to store student details and implement the following methods:
1. `getAverageGrade()`: This method should calculate and return the average grade of all the students in the class. The time complexity of this method should be O(n), where n is the number of students.
2. `getTopPerformingStudent()`:... | Here is an example implementation of the class in Java:
```java
import java.util.ArrayList;
import java.util.List;
class Student {
private int id;
private String name;
private int grade;
public Student(int id, String name, int grade) {
this.id = id;
this.name = name;
this.grad... | 22,645 |
Create a class called “Car” in Java with the following attributes and methods. The Car class should have an additional attribute called "color" which represents the color of the car. The color attribute should be a String type. The Car class should also have a method called "startEngine" which starts the engine of the ... | Here is the implementation of the Car class in Java:
```java
public class Car {
private String color;
private double fuelLevel;
public Car(String color) {
this.color = color;
this.fuelLevel = 0.0;
}
public boolean startEngine() {
if (fuelLevel > 0.5) {
System.o... | 22,778 |
Write a Java program to display a pattern of numbers in a pyramid shape. | Sure! Here's a Java program that displays a pattern of numbers in a pyramid shape:
```java
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
int count = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
... | 22,918 |
Write a Java code snippet to print the following line of text: “Hello, World!” but ensure that the word "World" is printed in reverse order. | Here is a Java code snippet that prints the line of text "Hello, World!" with the word "World" printed in reverse order:
```java
public class HelloWorld {
public static void main(String[] args) {
String message = "Hello, World!";
String[] words = message.split(" ");
StringBuilder reversedWo... | 22,992 |
Write a Java method that takes in a string and returns an array containing all the possible permutations of this string. Additionally, each permutation should only contain unique characters. | Here is a Java method that takes in a string and returns an array containing all the possible permutations of this string. Each permutation only contains unique characters.
```java
import java.util.ArrayList;
import java.util.List;
public class Permutations {
public static String[] getPermutations(String input) {... | 23,009 |
Create a program in Java to reverse a sentence while maintaining the order of the words.
For example, if the input sentence is "This is a sample sentence," the output should be "sentence sample a is This."
Provide a piece of erroneous code to mislead the candidates:
```
String[] words = sentence.split(" ");
for (int i... | Here is the corrected version of the program to reverse a sentence while maintaining the order of the words:
```java
import java.util.Scanner;
public class ReverseSentence {
public static void main(String[] args) {
// Get input sentence from user
Scanner scanner = new Scanner(System.in);
S... | 23,020 |
Create a Java code snippet that takes two integers as parameters and prints the larger one. Additionally, ensure that the program handles and outputs an error message if either of the input integers is negative. | Here's the Java code snippet that takes two integers as parameters and prints the larger one, while handling and outputting an error message if either of the input integers is negative:
```java
public class Main {
public static void main(String[] args) {
int num1 = 5; // replace with desired value
... | 23,025 |
Create a conditional statement in Java that prints "Welcome!" if the given argument is "Hi" and the length of the argument is greater than or equal to 2. | Here's an example of a conditional statement in Java that prints "Welcome!" if the given argument is "Hi" and the length of the argument is greater than or equal to 2:
```java
public class ConditionalStatementExample {
public static void main(String[] args) {
String argument = "Hi";
if (ar... | 23,123 |
Create a program in Java to check whether the given word is a palindrome or not. The program should also ignore any whitespace characters in the input word and should be case-insensitive. The input word will only contain alphabetic characters. | Here is a Java program that checks whether a given word is a palindrome or not, ignoring whitespace characters and being case-insensitive:
```java
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.ou... | 23,125 |
Create a Java program to list out all prime numbers between 1 and n, where n is a positive integer less than or equal to 100. Additionally, the program should display the sum of all prime numbers found. | Sure! Here's a Java program that lists out all prime numbers between 1 and n, where n is a positive integer less than or equal to 100. It also displays the sum of all prime numbers found.
```java
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner... | 23,171 |
Write a Java program to print 'Hello World' five times using a for loop. | Here is the Java program that prints 'Hello World' five times using a for loop:
```java
public class HelloWorld {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Hello World");
}
}
}
```
When you run this program, it will print 'Hello Worl... | 23,208 |
Write a Java program that searches an array for a given value and returns the index at which it is found. The array contains unique integers in ascending order. Implement a binary search algorithm to solve this problem.
int[] arr = {3, 4, 6, 7, 8, 10};
int searchValue = 8;
#Difficulty increased#
The original test was... | Here's an implementation of the binary search algorithm in Java:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int searchValue) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
... | 23,245 |
Write a Java program to replace all occurrences of a given character with '*'.
String = "Hello World!"
Character = 'o' | Here is the Java program to replace all occurrences of a given character with '*':
```java
public class ReplaceCharacter {
public static void main(String[] args) {
String str = "Hello World!";
char ch = 'o';
String result = replaceCharacter(str, ch);
System.out.println(result);
... | 23,373 |
Write a java program to print the frequencies of all characters in a string. However, you must implement this program using a custom data structure instead of using any built-in data structures like maps or hash tables. | Here is a Java program that uses a custom data structure to print the frequencies of all characters in a string:
```java
public class CharacterFrequencyCounter {
static class CharacterFrequency {
char character;
int frequency;
public CharacterFrequency(char character) {
this.c... | 23,407 |
Write Java code to calculate the sum of the first n Fibonacci numbers. | Here's a Java code to calculate the sum of the first n Fibonacci numbers:
```java
public class FibonacciSum {
public static int fibonacciSum(int n) {
if (n <= 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
int sum = 1;
int prev1 = 1;
... | 23,448 |
Write code in Java to find the sum of all the unique elements in an array. | Here is a Java code to find the sum of all the unique elements in an array:
```java
import java.util.HashSet;
public class SumOfUniqueElements {
public static int sumOfUniqueElements(int[] nums) {
// Create a HashSet to store unique elements
HashSet<Integer> uniqueElements = new HashSet<>();
... | 23,453 |
Create a Java program that takes two strings s and t as input and checks if t is an anagram of s. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. Your program should return true if t is an anagram of s and false otherwise.
Time Complexity Requirement: Your program should run... | Here's the Java program that checks if t is an anagram of s:
```java
import java.util.Arrays;
public class AnagramChecker {
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26]; // Assuming only... | 23,468 |
Write a Java program to find the common characters in two given strings and count the frequency of each common character. | Here is a Java program that finds the common characters in two given strings and counts the frequency of each common character:
```java
import java.util.HashMap;
import java.util.Map;
public class CommonCharacters {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "wor... | 23,479 |
Write a Java method that takes a string and an integer as input, and returns the string in reverse with the integer repeated at the end. The string can contain special characters and digits, and may have a maximum length of 100 characters. The integer should be a positive number between 1 and 1000. The method should ha... | Here is a Java method that takes a string and an integer as input and returns the string in reverse with the integer repeated at the end:
```java
public String reverseStringWithInteger(String inputString, int inputInteger) {
// Check if the input string is null or empty
if (inputString == null || inputString.i... | 23,481 |
Create an object-oriented program in Java to calculate the area and perimeter of a rectangle, with the following additional constraints:
- The program should include at least two classes, one for the rectangle and one for the main program.
- The rectangle class should have private instance variables for the length and... | Here is an example of an object-oriented program in Java that meets the given constraints:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
class Rectangle {
private double length;
private double width;
public double getLength() {
return length;
}
public void se... | 23,537 |
Create a Java method to print a binary tree in level order, but without using any additional data structures or recursion. | To print a binary tree in level order without using any additional data structures or recursion, you can use a queue to keep track of the nodes in each level. The algorithm follows these steps:
1. Create a queue and enqueue the root node of the binary tree.
2. While the queue is not empty, do the following:
a. Deq... | 23,550 |
Create a method to validate an email address in Java that also checks if the email address is from a specific domain (e.g., example.com). | Here's an example of a method in Java that validates an email address and also checks if it is from a specific domain:
```java
import java.util.regex.Pattern;
public class EmailValidator {
// Email validation regular expression pattern
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Z... | 23,569 |
Generate a Java program that creates a random array of 1000 integers ranging from 0 to 999. | Sure! Here's an example of a Java program that generates a random array of 1000 integers ranging from 0 to 999:
```java
import java.util.Random;
public class RandomArrayGenerator {
public static void main(String[] args) {
// Create a random object
Random random = new Random();
// Create a... | 23,623 |
Write a method in Java that takes a string as input and returns the number of vowels present in the string. | Here's a Java method that counts the number of vowels in a given string:
```java
public static int countVowels(String input) {
// Initialize a counter variable to keep track of the number of vowels
int count = 0;
// Convert the input string to lowercase to simplify comparison
String lowercaseInput... | 23,664 |
Create a Java program that calculates the probability of rolling a pair of dice and getting a sum greater than or equal to 8 and less than or equal to 12. | Here is a Java program that calculates the probability of rolling a pair of dice and getting a sum greater than or equal to 8 and less than or equal to 12:
```java
import java.util.Random;
public class DiceProbability {
public static void main(String[] args) {
int totalRolls = 1000000; // Number of times... | 23,670 |
Write a Java Program to print the Fibonacci numbers for a given range, with the additional requirement that the program must be implemented using a recursive approach. | Here is a Java program that uses a recursive approach to print the Fibonacci numbers for a given range:
```java
public class FibonacciRecursive {
public static void main(String[] args) {
int range = 10; // Set the range of Fibonacci numbers to be printed
System.out.println("Fibonacci Serie... | 23,674 |
Construct a regex in Java that matches a valid email address and also validates the domain name. | To construct a regex in Java that matches a valid email address and validates the domain name, you can use the following pattern:
```java
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
```
This regex pattern consists of the following parts:
- `^` - Beginning of... | 23,697 |
Write Java code to generate a square matrix of size n, where n is a positive integer less than or equal to 10. The elements in the matrix should be randomly generated integers ranging from -100 to 100. The code should also compute and print the sum of the main diagonal elements in the matrix. | Here is a Java code that generates a square matrix of size n, fills it with randomly generated integers ranging from -100 to 100, and computes and prints the sum of the main diagonal elements in the matrix:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int n... | 23,702 |
Construct a java method to convert alphabets to uppercase and count the number of occurrences of each alphabet in the string.
String str = "This is a great day"
Requirements:
- The method should have a time complexity of O(n), where n is the length of the input string.
- The method should have a space complexity of O... | Here's an example implementation of the requested method:
```java
import java.util.HashMap;
import java.util.Map;
public class AlphabetCounter {
public static Map<Character, Integer> countAlphabets(String str) {
Map<Character, Integer> countMap = new HashMap<>();
str = str.toUpperCase();
... | 23,750 |
Write a Java code to find the longest common prefix in a string array.
String [] arr = {"flower","flow","flight", "fleet"} | Here is a Java code that finds the longest common prefix in a string array:
```java
public class LongestCommonPrefix {
public static String findLongestCommonPrefix(String[] arr) {
if (arr == null || arr.length == 0) {
return "";
}
String prefix = arr[0]; // Start with t... | 23,783 |
Implement a switch-case statement in Java that takes in a string as input and performs different operations based on the value of the string.
Requirements:
- The input string can only contain lowercase alphabets (a-z).
- The switch-case statement should handle at least 10 different cases.
- Each case should perform a ... | Here is an example implementation of a switch-case statement in Java that meets the given requirements:
```java
public class SwitchCaseExample {
public static void main(String[] args) {
String input = "g";
switch (input) {
case "a":
System.out.println("Perform o... | 23,825 |
Create a two-dimensional array in Java with values corresponding to the given output. Each element in the array should be the sum of the previous two elements in the Fibonacci sequence. The output should be: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. | Here is the code to create a two-dimensional array in Java with values corresponding to the given output:
```java
public class FibonacciArray {
public static void main(String[] args) {
int[][] fibonacciArray = new int[1][10];
fibonacciArray[0][0] = 0;
fibonacciArray[0][1] = 1;
for ... | 23,864 |
Write a Java code snippet to calculate the area of a triangle, given three points. The points should not be collinear.
x1, y1 = 0, 0
x2, y2 = 5, 0
x3, y3 = 0, 5
The code should handle the case when the points are collinear and output an appropriate message. | Here's the Java code snippet to calculate the area of a triangle given three points:
```java
public class TriangleAreaCalculator {
public static void main(String[] args) {
int x1 = 0, y1 = 0;
int x2 = 5, y2 = 0;
int x3 = 0, y3 = 5;
double area = calculateTriangleArea(x1, y1, x2, y2... | 23,928 |
Create a Java program to print out the number of times a specific word appears in an array of sentences. The program should also consider variations in capitalization, meaning "Apple" and "apple" should be considered the same word.
array = ["I ate an apple", "I love apples", "I bought a banana", "Apples are delicious"]... | Here is a Java program that counts the occurrences of a specific word in an array of sentences, while ignoring variations in capitalization:
```java
public class WordCount {
public static void main(String[] args) {
String[] sentences = {"I ate an apple", "I love apples", "I bought a banana", "Apples are de... | 24,051 |
Create an array in Java and add the following elements: 5, 7, 3. Sort the array in ascending order and then print the elements in reverse order. | Here is the code to create an array, add elements, sort in ascending order, and print the elements in reverse order in Java:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Create an array
int[] array = {5, 7, 3};
// Sort the array in ascen... | 24,057 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.