instruction stringlengths 25 5.05k | output stringlengths 4 8.53k | __index_level_0__ int64 34 78.2k |
|---|---|---|
Write a Java method to swap the values of two integer variables without using a temporary variable. Additionally, handle the case where the input integers are equal and provide an error message for this scenario. | Here's a Java method that swaps the values of two integer variables without using a temporary variable and handles the case where the input integers are equal:
```java
public static void swapIntegers(int a, int b) {
if (a == b) {
System.out.println("Error: The input integers are equal.");
return;
... | 57,475 |
Please provide a Java program that searches for a certain element in an array and returns the indices of all occurrences of the element. The program should handle cases where the array is multidimensional or contains null values. The search should be case-insensitive if the array contains strings. The program should us... | Here is a Java program that meets all the requirements mentioned:
```java
public class ArraySearch {
public static <T> void searchArray(T[][] arr, T target) {
if (arr == null || target == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
for (int... | 57,497 |
Create a class in Java which computes the sum of the cube of even prime numbers between k and n, where k and n are positive integers. The program should be able to handle large values of k and n efficiently. | Here's an example implementation of a Java class that computes the sum of the cube of even prime numbers between k and n efficiently:
```java
import java.math.BigInteger;
public class EvenPrimeCubesSum {
public static BigInteger computeSumOfEvenPrimeCubes(int k, int n) {
BigInteger sum = BigInteger.ZERO;
... | 57,499 |
Write a Java program that accepts user input for an array of integers and passes it to a method. The method should return the product of all the prime numbers in the array and print the result. | Here is an example of a Java program that accepts user input for an array of integers and passes it to a method. The method then calculates the product of all the prime numbers in the array and prints the result:
```java
import java.util.Scanner;
public class PrimeProduct {
public static void main(String[] args) ... | 57,539 |
Create a program using Java to print the sum of the following ten prime numbers.
int a = 2;
int b = 3;
int c = 5;
int d = 7;
int e = 11;
int f = 13;
int g = 17;
int h = 19;
int i = 23;
int j = 29; | Here is a Java program that calculates the sum of the given ten prime numbers:
```java
public class PrimeNumberSum {
public static void main(String[] args) {
int a = 2;
int b = 3;
int c = 5;
int d = 7;
int e = 11;
int f = 13;
int g = 17;
int h = 19;
... | 57,543 |
Modify the following Java code to debug and execute properly. Additionally, ensure that the program prints the phrase "Hello, world!" instead of "Hello world".
public class HelloWorld {
public static void main(String[] args) {
System.out.print("Hello, world");
}
} | public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
} | 57,551 |
Construct a program in Java for solving the Tower of Hanoi puzzle, with the additional requirement of finding the minimum number of moves needed to solve the puzzle. Additionally, implement a feature that allows the user to input the number of disks in the puzzle, with a minimum of 3 disks and a maximum of 10 disks. | Here is a Java program that solves the Tower of Hanoi puzzle and calculates the minimum number of moves needed. It also allows the user to input the number of disks in the puzzle.
```java
import java.util.Scanner;
public class TowerOfHanoi {
public static void main(String[] args) {
Scanner scanner = new S... | 57,553 |
Increase the difficulty by adding new constraints and requirements to the original problem:
Implement a class in Java that retrieves data from a database and performs CRUD (Create, Read, Update, Delete) operations on the data.
Requirements:
1. The class should have methods for connecting to the database, executing SQ... | Additional Constraints and Requirements:
9. Implement input validation for user-provided data to prevent SQL injection attacks and ensure data integrity.
10. Implement support for data encryption and decryption for sensitive information stored in the database.
11. Implement support for database replication and synchro... | 57,568 |
Write a Java method called "sum" that takes two parameters, number1 and number2, both of type int. The method should return the sum of the two numbers. Additionally, the method should only accept positive integers as input, and should throw an IllegalArgumentException if either number1 or number2 is negative or zero. T... | public class OverflowException extends RuntimeException {
public OverflowException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
int number1 = 10;
int number2 = 20;
int sum = sum(number1, number2)... | 57,618 |
Create a class in Java that performs the following task: print out all characters of a given string along with their position in the string, but only for vowels. Additionally, count and print the number of vowels in the string and display the vowels in uppercase. | Here is an example of a Java class that performs the given task:
```java
public class VowelCounter {
public static void main(String[] args) {
String inputString = "Hello, World!";
int vowelCount = 0;
System.out.println("Input String: " + inputString);
// Loop through each characte... | 57,639 |
Select the correct answer from the following options to complete the Java code:
int a = 12, b = 6;
int result = __________;
Options:
A) a / b + (b % a);
B) a % b + (b / a);
C) (a + b) / (a - b);
D) (a * b) / (a + b); | B) a % b + (b / a); | 57,688 |
Write a Java program to categorize each of the following strings as a palindrome or not.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization.
Your program should:
1. Declare a method called "isPalindrome... | Here's the Java program that categorizes each of the given strings as a palindrome or not:
```java
public class PalindromeChecker {
public static void main(String[] args) {
Object[] values = {"madam", "DAD", "superman", "abcdef", 12321, 12345};
for (Object value : values) {
System.out.... | 57,712 |
Write a Java code to encrypt a password using `bcrypt` hash algorithm with a cost factor of 12.
String password = "password123";
Hint: The `bcrypt` algorithm is considered to be more secure than `sha256` and allows for a cost factor to be specified for the hash. | import org.mindrot.jbcrypt.BCrypt;
public class PasswordEncryptor {
public static void main(String[] args) {
String password = "password123";
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(12));
System.out.println("Original password: " + password);
System.ou... | 57,713 |
Given a sentence, create a method to capitalize every word in the sentence. The sentence will consist of only lowercase letters and spaces, and will not contain any punctuation marks or special characters. Additionally, the sentence will now contain numbers in the form of words (e.g. "one", "two", "three"). The sentenc... | One possible implementation of the method in Java could be:
```java
public static String capitalizeSentence(String sentence) {
String[] words = sentence.split(" ");
StringBuilder capitalizedSentence = new StringBuilder();
for (String word : words) {
if (word.equals("one") || word.equals("two")... | 57,728 |
Create a method to find the shortest word in a given array of strings. The method should ignore any words that contain digits, special characters, or vowels. Additionally, the method should handle the case when two or more words have the same shortest length by returning the word that occurs first in the array. | Here's a possible implementation in Java:
```java
public static String findShortestWord(String[] words) {
String shortestWord = null;
int shortestLength = Integer.MAX_VALUE;
for (String word : words) {
// Skip words with digits, special characters, or vowels
if (word.matches(".*\\d.*")... | 57,736 |
Write a Java program that calculates the sum of all odd numbers from 1 to 1000 and prints the result. | Here is a Java program that calculates the sum of all odd numbers from 1 to 1000 and prints the result:
```java
public class OddNumberSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; i += 2) {
sum += i;
}
System.out... | 57,738 |
Create a program in Java that takes an array with two positive prime numbers as input and prints the result of raising the first number to the power of the second number. The program should handle cases where the input array does not contain two positive prime numbers and display an error message in such cases.
Additi... | Here is the Java program that meets the requirements:
```java
import java.util.Arrays;
public class PrimePower {
public static void main(String[] args) {
int[] input = {5, 2}; // Example input array
try {
int result = calculatePower(input);
System.out.println("Result: " + ... | 57,773 |
Create a method named 'combine' to combine two strings, where the length of each string is at most 100 characters. String str1 = "Hello"; String str2 = "World"; Ensure that the combined string does not exceed a length of 150 characters. | Here is an example implementation of the 'combine' method in Java:
```java
public static String combine(String str1, String str2) {
if (str1.length() + str2.length() <= 150) {
return str1 + str2;
} else {
int maxLength = 150 - str1.length();
return str1 + str2.substring(0, maxLength);
... | 57,814 |
Write a program in a programming language of your choice that demonstrates the concept of static variables in a multi-threaded environment. The program should have a class with a static variable and two methods. The first method should increment the static variable by 1, and the second method should print the value of ... | Sure! Here's an example program in Java that demonstrates the concept of static variables in a multi-threaded environment:
```java
import java.util.concurrent.atomic.AtomicInteger;
class MyClass {
static AtomicInteger counter = new AtomicInteger(0);
static synchronized void increment() {
counter.incr... | 57,838 |
Given a nested XML structure, parse and extract the value of a specific element, while also checking if the book is available for borrowing.
XML Structure:
<library>
<section id="1">
<category>Programming</category>
<books>
<book id="1" available="yes">
<title>Python fo... | Here's a Python program that parses the given XML structure and extracts the title, author, and availability status of a specific book based on the user input:
```python
import xml.etree.ElementTree as ET
xml_data = '''
<library>
<section id="1">
<category>Programming</category>
<books>
... | 57,844 |
Create a series of nested for loops in Java to print the prime numbers between 1 and 100 in descending order on separate lines. Additionally, modify the code to skip printing any prime numbers that end with the digit 5. | Here's the code to print the prime numbers between 1 and 100 in descending order:
```java
public class PrimeNumbers {
public static void main(String[] args) {
for (int i = 100; i >= 1; i--) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public stat... | 57,847 |
Compose a for loop in Java to print the numbers from 4 to 1 on separate lines, but only if the number is divisible by both 2 and 3. Otherwise, print "Skipped: " followed by the number on a new line. Ensure that the loop runs exactly 5 times. | Here is the for loop in Java to achieve the given task:
```java
for (int i = 4; i >= 1; i--) {
if (i % 2 == 0 && i % 3 == 0) {
System.out.println(i);
} else {
System.out.println("Skipped: " + i);
}
}
```
Explanation:
- The loop starts with `int i = 4`, and it continues as long as `i` is gr... | 57,852 |
Write a Java program that prompts the user to enter two strings and outputs whether the two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase.
In addition to the requirements of the given test, you should now also consider the frequency of characters in t... | Here's a Java program that meets all the requirements:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first string: ");... | 57,869 |
Create a set in Java from a given array of numbers. The set should only contain unique elements in ascending order. The input array may contain negative numbers as well.
Array: [2, -3, 5, 4, -2, 3, 5, -4]
Time Complexity Requirement: O(n), where n is the number of elements in the input array.
Space Complexity Requirem... | Here is a Java code that creates a set from the given array using a divide and conquer algorithm:
```java
import java.util.HashSet;
import java.util.Set;
public class SetFromArray {
public static Set<Integer> createSet(int[] arr) {
return createSet(arr, 0, arr.length - 1);
}
private static Set<I... | 57,902 |
Construct a method in Java that takes in an integer as input and returns true if the integer is a prime number, and false otherwise. The method should have a time complexity of O(sqrt(n)). | Here is an example of a method in Java that checks if a given integer is a prime number using O(sqrt(n)) time complexity:
```java
public class PrimeNumberChecker {
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return... | 57,922 |
Write a code in Java that will get all the prime numbers from an array of integers and store them in a separate array. Additionally, the code should display the sum of all the prime numbers found. | Here is a Java code that fulfills the given requirements:
```java
import java.util.ArrayList;
import java.util.Arrays;
public class PrimeNumbers {
public static void main(String[] args) {
int[] numbers = {2, 3, 5, 6, 7, 11, 13, 17, 19, 23};
ArrayList<Integer> primeNumbers = new ArrayList<>();
... | 57,934 |
In Java, write a program that prompts the user to enter a phrase and then prints the phrase in reverse order, but only if the phrase is a palindrome. If the phrase is not a palindrome, the program should print an error message instead. | import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a phrase: ");
String phrase = scanner.nextLine();
scanner.close();
// Remove all spaces and convert to lowercase fo... | 57,950 |
Please create a class called Employee in Java which contains the name, age, salary, and department of the employee. Implement methods to calculate the yearly bonus based on the employee's salary and department. The bonus should be calculated as follows:
- For employees in the sales department, the bonus is 5% of their ... | Here's an example implementation of the Employee class in Java:
```java
public class Employee {
private String name;
private int age;
private double salary;
private String department;
public Employee(String name, int age, double salary, String department) {
validateName(name);
vali... | 57,962 |
Please write a Java program that converts a given string to all lowercase letters, removes any duplicate characters, and sorts the characters in descending order based on their frequency.
1. Start by declaring a string variable called "myString" and assign it the value "HeLlO WoRlD".
2. Create a new string variable ca... | ```java
import java.util.*;
public class StringConversion {
public static void main(String[] args) {
String myString = "HeLlO WoRlD";
String lowercaseString = "";
TreeMap<Character, Integer> charFrequency = new TreeMap<>();
for (char c : myString.toCharArray()) {
if (c ... | 57,969 |
Develop a Java program that prints all the prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. | Here is a Java program that prints all the prime numbers up to a given limit using the Sieve of Eratosthenes algorithm:
```java
import java.util.Arrays;
public class PrimeNumbersSieve {
public static void main(String[] args) {
int limit = 100; // define the limit
boolean[] primes = sieveOfEratos... | 58,027 |
Design a multithreaded program to generate all prime numbers between 1 and 1,000,000, where each thread is responsible for checking a specific range of numbers. The program should use a thread-safe data structure to store the prime numbers and ensure that the prime numbers are generated in ascending order. | Here's an example implementation of a multithreaded program in Java to generate all prime numbers between 1 and 1,000,000:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
cl... | 58,124 |
Implement a matrix multiplication program in Java. Additionally, your program should also handle matrix addition and subtraction. You are not allowed to use any built-in matrix operations or libraries.
1. Your program should take input from the user for two matrices, Matrix A and Matrix B, with dimensions m x n and n ... | ```java
import java.util.Scanner;
public class MatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Take input for Matrix A
System.out.print("Enter the number of rows for Matrix A: ");
int rowsA = scanner.nextInt();
Syste... | 58,188 |
Write a program in Java that takes a string as input and reverses the order of the words, while preserving the position of any punctuation marks and whitespace. For example, the input "Hello, world!" should return "!dlrow ,olleH". | Here's a program that takes a string as input, reverses the order of the words while preserving the position of any punctuation marks and whitespace.
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReverseWords {
public static void main(String[] args) {
String input = ... | 58,195 |
In Java, construct a data structure for storing employee information, including name, age, phone number, address, salary, and employee ID. Additionally, ensure that the salary field can only accept positive values, and the phone number field follows a specific format of XXX-XXX-XXXX. | Here is an example of how you can create a data structure in Java for storing employee information with the given requirements:
```java
public class Employee {
private String name;
private int age;
private String phoneNumber;
private String address;
private double salary;
private int employeeId... | 58,196 |
Write a method in Java to return a reversed version of a given string, but only reverse the alphabetical characters in the string while keeping the non-alphabetical characters in their original positions. Additionally, make sure the method is case-insensitive, meaning that the reversal should work for both uppercase an... | Here is the implementation of the method:
```java
public class ReverseAlphabeticalString {
public static String reverseAlphabetical(String input) {
char[] chars = input.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
// Ski... | 58,224 |
Create a Java program that prints out the sum of the numbers in the array.
int[] numbers = {1, 2, 3 , 4, 5}; | public class SumOfArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3 , 4, 5};
int sum = 0;
for(int i=0; i < numbers.length;i++) {
sum = sum + numbers[i];
}
System.out.println("The sum of numbers in the given array is: " + sum);
}
} | 58,271 |
Create a Java program that prints out the contents of a given two-dimensional array.
int[][] arr = {{1,2},{3,4},{5,6}} | public class TwoDArray {
public static void main(String[] args) {
int[][] arr = {{1,2},{3,4},{5,6}};
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
} | 58,278 |
Sum up the numbers in the array in Javascript.
arr = [1,2,3,4,5] | let sum = arr.reduce((total, num) => total + num);
console.log(sum); // 15 | 58,296 |
What is the purpose of a constructor in a class in Java? | The purpose of a constructor in a class in Java is to initialize an object of that class. A constructor is a special kind of method that is used to create an object of its associated class. When an object of the class is created, the constructor is used to set the initial state of the object. | 58,311 |
Create a class in Java named Puppy that has two instance variables, age and name and two methods, bark and sleep. | public class Puppy {
// Instance Variables
String name;
int age;
// Constructor
public Puppy(String name, int age){
this.name = name;
this.age = age;
}
// Methods
public void bark(){
System.out.println("Woof Woof!");
}
public void sleep(){
Sys... | 58,325 |
Parse the string and return the number of unique alphabets in the string.
StringInput = "apple" | int count = 0;
for (int i = 0; i < StringInput.length(); i++) {
if ((StringInput.charAt(i) >= 'a' && StringInput.charAt(i) <= 'z') || (StringInput.charAt(i) >= 'A' && StringInput.charAt(i) <= 'Z')) {
count++;
}
}
System.out.println("Number of unique alphabets: " + count); | 58,326 |
Write a Java program to reverse a given string. | public class ReverseString
{
public static void main(String[] args)
{
String input = "Hello";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = inp... | 58,358 |
Write a Java program to generate random numbers | import java.util.Random;
public class GenerateRandom {
public static void main(String[] args)
{
Random rand = new Random();
// Generate random integers in range 0 to 999
int x = rand.nextInt(1000);
System.out.println("Random Integers: " + x);
// Gen... | 58,362 |
Create a Java program which takes an integer array as a parameter, sorts the array in ascending order, and returns the sorted array.
[3, 5, 9, 1, 6] | public int[] SortIntegerArray(int[] nums)
{
Arrays.sort(nums);
return nums;
} | 58,387 |
Create a Java program to take a given string and replace all occurrences of a given letter with another given letter
'bbac', 'b', 'a' | public String ReplaceLetters(String str, char oldChar, char newChar) {
return str.replace(oldChar, newChar);
} | 58,390 |
Write code in Java to generate the Fibonacci sequence up to N numbers.
N = 10 | public class Fibonacci {
public static void FibonacciN(int n) {
int i, f=0, s=1;
if (n == 1)
System.out.print(f+ " ");
else {
System.out.print(f+" "+s+" ");
for (i = 2; i < n; i++) {
int next = f + s;
Sy... | 58,411 |
Write code in Java to sort an array of integers in ascending order.
[5, 2, 8, 10, 4, 9] | public static void sortAscending(int[] arr) {
for(int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int tmp = arr[i];
arr[i] = arr[min];
arr[min] ... | 58,413 |
Write a Java program to calculate the sum of the two given integers.
Integers: 4 and 9 | public static int addIntegers(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
int x = 4, y = 9;
int sum = addIntegers(x, y);
System.out.println("Sum is: "+sum);
} | 58,428 |
Write a Java program to print out the first n prime numbers | public static void printPrimeNumbers(int n)
{
int num;
int count=0;
for (int i = 2; i <= n;)
{
num=0;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
num++;
br... | 58,485 |
Write a Java program to find the largest element in a given array. | public class Largest {
static int getLargest(int[] inputArray){
int largest = inputArray[0];
for(int i = 1; i < inputArray.length; i++){
if(inputArray[i] > largest){
largest = inputArray[i];
}
}
return largest;
}
pub... | 58,587 |
Create a method in Java to return the largest of three numbers. | public static int max(int num1, int num2, int num3) {
int max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
return max;
} | 58,590 |
Compare the two strings character-by-character and return the number of differences using Java.
String 1: Hello
String 2: Halle | int diff = 0;
for (int i=0; i < Math.min(str1.length(), str2.length()); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
diff++;
}
}
return diff; | 58,594 |
Edit the Java code to filter out the persons whose age is less than 18.
List<Person> persons = new ArrayList<>();
for (Person person : persons) {
System.out.println(person.getName());
} | List<Person> persons = new ArrayList<>();
for (Person person : persons) {
if (person.getAge() >= 18) {
System.out.println(person.getName());
}
} | 58,602 |
Write code in Java to create a linked list. | class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
class LinkedList{
Node head;
public void insert(int data){
Node node = new Node(data);
if (head == null) {
head = node;
}
else {
... | 58,649 |
Construct a Java program for sorting a given array in ascending order. | public class ArraySort {
public static int[] sortArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp ... | 58,651 |
Implement a Java program for finding the index of an element in a sorted array. | public int binarySearch(int[] arr, int val){
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) /2 ;
if (arr[mid] == val)
return mid;
else if (arr[mid] < val)
left = mid + 1;
else
right = mi... | 58,684 |
Create a Java program to check for a palindrome. | public class Palindrome {
public static boolean isPalindrome(String str){
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters toc compare
while (i < j) {
// If there is a m... | 58,692 |
Convert the following code from Swift to Java.
let age = 25 | int age = 25; | 58,724 |
Create a for loop in Java that iterates over the given array and prints the values.
Array: int[] arr = {1, 2, 3, 4, 5}; | for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
} | 58,728 |
Create a program in Java to print out the Fibonacci sequence of numbers up to 10. | public class Fibonacci {
public static void main(String[] args) {
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);
for(i=2;i<count;++i) {
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
} | 58,733 |
Write a code to implement Selection Sort in Java | public class SelectionSort {
public static void sort(int[] arr) {
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1... | 58,748 |
Write a Java program that takes two strings as inputs and checks if one string is a rotation of the other. | import java.util.Arrays;
class GFG {
// Function to check if two strings are
// rotations of each other or not
static boolean areRotations(String str1, String str2)
{
// There lengths must be same and str2 should
// be a substring of str1 concatenated with
// str1.
... | 58,765 |
Create an array in Java with 10 floating-point values and output the average of these values. | // Create an array
float arr[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1};
// Calculate average
float sum = 0;
for (int i = 0; i < 10; i++) {
sum += arr[i];
}
float average = sum / 10;
System.out.println("Average of the array values: " + average); | 58,769 |
Find the power of a number using an iterative approach in Java. | public static int power(int base, int exp)
{
int result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
} | 58,770 |
Create a loop to print hello world 5 times. | for (int i = 0; i < 5; i++){
System.out.println("Hello World!");
} | 58,779 |
Suppose there is an array of numbers. Write a Java program to sort the array in ascending order.
[3,8,5,1,2,6,4] | public class SortAscending {
public static void main(String[] args)
{
int[] numbers = {3,8,5,1,2,6,4};
int temp = 0;
for (int i = 0; i < numbers.length; i++) {
for (int j = i+1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
//... | 58,795 |
Modify the above program to sort the array in descending order.
[3,8,5,1,2,6,4] | public class SortDescending {
public static void main(String[] args)
{
int[] numbers = {3,8,5,1,2,6,4};
int temp = 0;
for (int i = 0; i < numbers.length; i++) {
for (int j = i+1; j < numbers.length; j++) {
if (numbers[i] < numbers[j]) {
/... | 58,796 |
Write a Java program to print the sum of all integers from 1 to given integer.
integer = 5 | public class SumIntegers {
public static void main(String[] args) {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum of integers from 1 to "+n+": "+sum);
}
}
// Output: Sum of integers from 1 to 5: 15 | 58,850 |
Write a Java program to find the sum of elements in a 3x3 matrix. | // Java program to find sum of elements in a matrix
public class Matrix
{
public static void main(String[] args)
{
// Initialize matrix
int[][] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
// Initialize sum
int sum = 0;
// Compute sum of elements
for (int i = 0; i < 3; i++)
fo... | 58,889 |
Describe in one sentence what is wrong with the following Java code.
public class Main {
public static void main(String[] args) {
int y;
y = 10 + 5;
y -= 30;
}
} | The code does not do anything with the value of y, meaning that it is not being used. | 58,890 |
Name three types of looping structures in Java. | The three types of looping structures in Java are for-loops, while-loops, and do-while loops. | 58,899 |
Implement a stack data structure in Java. | // Stack class
class Stack
{
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack
boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}
boolean push(int x)
{
if (top >= (MAX-1))
{... | 58,923 |
Create a Java class that prints the Fibonacci sequence between 0 and 10. | public class Fibonacci {
public static void main(String[] args) {
printFibonacci();
}
public static void printFibonacci() {
int n1 = 0;
int n2 = 1;
int n3;
System.out.print(n1 + " " + n2);
for (int i = 0; i < 8; i++) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2... | 58,925 |
Explain how to implement a heap sort algorithm in Java. | // To implement a heap sort algorithm in Java:
// 1. Build a min heap from the input data.
// 2. At the top of the heap, obtain the minimum element.
// 3. Exchange the minimum element with the last element of the heap.
// 4. Reduce the size of the heap by one and heapify the root of the heap.
// 5. Repeat steps 2-4 unt... | 58,940 |
Create a Java program that reads two numbers from the user and prints the sum. | import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int num1 = sc.nextInt();
System.out.println("Enter second number:");
int num2 = sc.nextInt();
int sum = num1 + num2;
System.out.println("The s... | 58,961 |
Write a for loop in Java to print all the numbers in a given list.
int[] list = {21, 34, 54, 77, 92}; | for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
} | 58,967 |
Modify the following Java program to find the area of a rectangle.
public class Area
{
public static void main(String[] args)
{
double radius = 10;
double area = 3.14 * radius * radius;
System.out.println("The area of the circle = "+area);
}
} | public class Area
{
public static void main(String[] args)
{
double length = 10;
double width = 5;
double area = length * width;
System.out.println("The area of the rectangle = "+area);
}
} | 58,978 |
Analyze the given Java code and identify the errors.
public class TestClass {
public static void main (String[] args) {
int x = 10;
int y = 20
int z = x + y;
system.out.println("The sum is: " + z);
}
} | The errors are:
1. The semicolon at the end of line 2 is missing.
2. The line 4 should be `System.out.println("The sum is: " + z);` (the capital S is missing).
3. The line 5 is an extra line which should be removed. | 59,003 |
Create a Java 8 Stream to filter a list of objects by a given field.
[
{'name': 'John', 'age': 20},
{'name': 'Smith', 'age': 30},
{'name': 'Bill', 'age': 40}
] | List<Object> list = Arrays.asList({
{'name': 'John', 'age': 20},
{'name': 'Smith', 'age': 30},
{'name': 'Bill', 'age': 40}
});
Stream<Object> stream = list.stream();
// Filter records whose age greater than 25
stream.filter(record -> (int) record.get("age") > 25).forEach(System.out::println); | 59,025 |
Design a class in Java that can store student information. | public class Student {
private String name;
private int age;
private String course;
public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}
public void setName(String name) {
this.name = name;
}
public String getName(){
return... | 59,032 |
Create a class in Java that can store a list of students and the courses they are enrolled in. | public class StudentList {
private ArrayList<Student> students;
private ArrayList<String> courses;
public StudentList() {
this.students = new ArrayList<Student>();
this.courses = new ArrayList<String>();
}
public void addStudent(Student student) {
this.students.add(student);
}
public void... | 59,033 |
Design a class in Java that can store a list of books and their associated authors. | public class BookCollection {
private ArrayList<Book> books;
private ArrayList<String> authors;
public BookCollection() {
this.books = new ArrayList<Book>();
this.authors = new ArrayList<String>();
}
public void addBook(Book book) {
this.books.add(book);
}
public void addAuthor(String aut... | 59,036 |
Change this existing Java code to generate the "Jesus Christ" string.
String str = "Holy"; | String str = "Holy";
String jesusChrist = str + " " + "Jesus Christ";
System.out.println(jesusChrist); | 59,054 |
Write a method that prints out a square of size n.
n=5 | public static void printSquare(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print("* ");
}
System.out.println();
}
}
// Output:
/*
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
*/ | 59,055 |
Write a Java Method that takes an array of integers and returns true if the array is sorted in ascending order.
array = [7, 18, 24, 55, 98] | public static boolean isSorted(int[] array) {
int n = array.length;
int temp = array[0];
for (int i = 1; i < n; i++) {
if (temp > array[i])
return false;
temp = array[i];
}
return true;
} | 59,056 |
Write a method that prints out all the prime numbers between 1 and 100. | public static void printPrimeNumbers(){
System.out.println("Prime numbers between 1 to 100 are : ");
for (int i = 1; i <= 100; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
... | 59,059 |
Demonstrate how to use an arraylist in Java. | import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an arraylist
ArrayList<String> list = new ArrayList<String>();
// Adding elements to the list
list.add("Adam");
list.add("Bob");
list.add("Charlie")... | 59,060 |
Write a Java method that takes a string and prints out the number of occurrences of each letter in the string.
String = "adda123de3f" | public static void printLetterOccurrences(String str) {
int[] alphabet = new int[26];
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
alphabet[str.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (alphabet[i] > 0) {
... | 59,063 |
Implement an algorithm to reverse a string in Java. | public static String reverseString(String s) {
char[] arr = s.toCharArray();
int n = arr.length;
for (int i = 0; i < n/2; i++) {
char temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
return new String(arr);
} | 59,068 |
Create a Java class to represent a TV show. | public class TVShow {
private String title;
private String network;
private String genre;
private int episodes;
public TVShow(String t, String n, String g, int e) {
title = t;
network = n;
genre = g;
episodes = e;
}
public String getTitle() {
return title;
}
public String... | 59,073 |
Develop a code in Java to calculate the BMI given the height and weight of a person. | public double calculateBMI(double height, double weight){
double bmi;
height = height/100;
bmi = weight / Math.pow(height, 2);
return bmi;
} | 59,077 |
Count the number of vowels in a sentence.
"Hi there, how are you doing?" | int countVowels = 0;
String sentence = "Hi there, how are you doing?";
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == 'a' || sentence.charAt(i) == 'e' || sentence.charAt(i) == 'i'
|| sentence.charAt(i) == 'o' || sentence.charAt(i) == 'u') {
countVowels++;
}
}
System.out.pri... | 59,079 |
Generate a random string of length 8 that only contains alphabets. | // Initialize an array containing all the letters of the alphabet
String[] alphabet = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String randomString = "";
Random random = new Random();
for (int i=0; i<8; i... | 59,081 |
Fill in the blanks at the end of the Java code to find the sum of an array.
public int sumArray(int[] arr){
int sum = 0;
______________
______________
return sum;
} | public int sumArray(int[] arr){
int sum = 0;
for(int i=0; i<arr.length;i++){
sum+=arr[i];
}
return sum;
} | 59,083 |
Describe the general syntax of an if statement in Java. | In Java, the syntax of an if statement is as follows:
if (condition) {
// Code to execute if condition is true
} | 59,084 |
You should create a Java program to implement a binary search. | public class BinarySearch
{
// Returns index of x if it is present in arr[l..
// r], else return -1
public int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle its... | 59,119 |
What is the difference between a for loop and a while loop in Java? | The main difference between for and while loop is that for loop is used when we already know the number of times the loop should iterate, while a while loop is used when the number of iterations is not known in advance. Another difference is that for loop is more convenient for looping through arrays/collections of obj... | 59,135 |
What is the meaning of static in Java? | In Java, the static keyword is used to indicate that an entity is associated with a class rather than an instance of a class. It can be used to denote class variables, class methods and other class elements, and is also used in various access modifiers. Static members are associated with the class itself, rather than a... | 59,139 |
Construct an if-else statement in Java for printing the square root of a given number. | if (x >= 0) {
System.out.println(Math.sqrt(x));
} else {
System.out.println("The number is negative");
} | 59,162 |
Implement the following algorithm in Java.
// Bubble sort algorithm
for i in 0 to n-1
for j in 0 to n-i-1
if array[j] > array[j+1]
swap array[j] and array[j+1] | public void bubbleSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} | 59,188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.