instruction stringlengths 25 5.05k | output stringlengths 4 8.53k | __index_level_0__ int64 34 78.2k |
|---|---|---|
Debug the following Java code to return the number of elements in the list.
ArrayList<String> valueList = new ArrayList<String>();
valueList.add("Apple");
valueList.add("Banana");
valueList.add("Orange");
System.out.println("Number of elements: " + valueList.length); | ArrayList<String> valueList = new ArrayList<String>();
valueList.add("Apple");
valueList.add("Banana");
valueList.add("Orange");
System.out.println("Number of elements: " + valueList.size(); | 64,783 |
Using for loop in Java, print even numbers from 20 to 30. | for (int i=20; i<=30; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
} | 64,791 |
Turn the following pseudocode into a Java method.
for n = 2 to 10
print (n * 2) | public void printMultiples(int start, int end) {
for (int n=start; n <= end; n++) {
System.out.println(n*2);
}
} | 64,807 |
Which library should be used to process data in Scala? | The Apache Spark library is the most common library used to process data in Scala. Apache Spark provides an easy-to-use, distributed environment for analytics and data processing applications. It offers APIs in Java, Python, and Scala, allowing users to neatly integrate data processing with high-level programming langu... | 64,822 |
Write a Java program to print binary numbers from 0 to 15. | public class Binary {
public static void main(String[] args) {
for (int i = 0; i <= 15; i++) {
System.out.println(Integer.toBinaryString(i));
}
}
} | 64,842 |
Find and delete duplicate elements from a given array in Java.
array = [1, 2, 3, 2, 4] | public static int[] deleteDuplicates(int[] array) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (!list.contains(array[i])) {
list.add(array[i]);
}
}
int[] output = list.stream().mapToInt(Integer::intValue).toArray();
... | 64,844 |
Create a Java program to find the area and circumference of a circle with a given radius. | public class Circle
{
public static void main(String[] args)
{
double radius = 6.2;
double area = Math.PI * radius * radius;
double circumference = 2 * Math.PI * radius;
System.out.println("Area = " + area);
System.out.println("Circumference = " + circumference);
}
... | 64,851 |
Write a Java code snippet that takes a URL as input and prints the content of the page. | import java.net.URL;
import java.util.Scanner;
public class UrlReader {
public static void main(String[] args) throws Exception {
String urlString = args[0];
URL url = new URL(urlString);
Scanner s = new Scanner(url.openStream());
while (s.hasNextLine()) {
System.out.... | 64,853 |
Create a Java program to find the max number within a list. | public static int findMax(int[] array) {
int max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
} | 64,857 |
Write a Java code to create an arraylist. | // Code to create an ArrayList in Java
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
// create an arraylist
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("C++");
list.add("Python");
System.out.printl... | 64,868 |
Design a data structure in Java to store students' marks in an examination | import java.util.HashMap;
// Data structure to store Marks
class Marks {
int physicsMarks;
int chemistryMarks;
int mathsMarks;
};
// HashMap to store Student's Marks
HashMap<String, Marks> marksHashMap = new HashMap<>();
// Function to store Student's marks
void storeMarks(String studentId, in... | 64,899 |
Design an algorithm in Java for solving a linear search problem. | // Returns index of x if it is present in arr[],
// else return -1
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
} | 64,905 |
What method is used to add an element to a stack in Java? | In Java, the method used to add an element to a stack is push(). This method adds an element to the top of the stack and increases the stack size by one. | 64,908 |
How can a class be extended in Java? | In Java, a class can be extended using the keyword "extends". This allows a new class to inherit all the variables, methods and constructors of another class. Additionally, the new class will have all the properties of its parent class as well as any new code defined in the new class. | 64,910 |
Rewrite the following code to use more efficient loops.
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.println("hi");
}
} | for (int i = 0; i < 100; i++) {
System.out.println("hi");
} | 64,926 |
What is the purpose of the for-each loop in Java? | The for-each loop in Java is a type of loop that is used to iterate over a collection, such as an array or a list. The for-each loop simplifies the process of writing loops and makes them more readable. It also allows the loop to run faster, since the loop variable does not need to be updated or declared each time thro... | 65,016 |
Using Java, access the value of the second dictionary key in "myDict".
myDict = {"key1": "value1", "key2": "value2", "key3": "value3"} | String value2 = myDict.get("key2"); | 65,045 |
Write code in Java to generate a random number between 12 and 23. | // Create an instance of Random class
Random rand = new Random();
// Generate a random number between 12 and 23
int rand_num = rand.nextInt(11) + 12;
// Print the random number
System.out.println("Random number: " + rand_num); | 65,050 |
Write a method in Java that returns an array of the first N prime numbers.
n=10 | public static int[] getFirstNPrimes(int n) {
int[] primes = new int[n];
int count = 0;
int num = 2;
while (count < n) {
if (isPrime(num)) {
primes[count] = num;
count++;
}
num++;
}
return primes;
}
// Utility functon to check whether a numbmer is prime or not
boolean isPrime(in... | 65,052 |
In Java, write code to remove all empty elements from an array.
arr = [1, 2, 3, "", 4, 5, "", 6] | List<String> nonEmpty = Arrays.stream(arr)
.filter(x -> !x.equals(""))
.collect(Collectors.toList()); | 65,055 |
Rewrite the Java code to a more efficient version.
public class Sum {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum = sum + i;
}
System.out.println(sum);
}
} | public class Sum {
public static void main(String[] args) {
int sum = 0;
int n = 10;
sum = (n * (n + 1)) / 2;
System.out.println(sum);
}
} | 65,081 |
Build a graphical user interface using Java. | import java.awt.*;
import javax.swing.*;
public class GUIExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GUI Example");
frame.setSize(400, 600);
JPanel panel = new JPanel();
JLabel label = new JLabel("This is a simple GUI.");
JButton button ... | 65,086 |
Suggest a method in Java to compare two strings. | The easiest way to compare two strings in Java is to use the built-in String class's equals() method. This method compares all characters in the strings, and returns true if the strings are equal or false otherwise. For example, given the strings "Hello" and "Goodbye", the following code would evaluate to false:
Strin... | 65,117 |
Write a Java program to find the largest number among three numbers entered by the user. | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter three numbers:");
int n1 = input.nextInt();
int n2 = input.nextInt();
int n3 = input.nextInt();
int r... | 65,163 |
Rewrite the given code in a different language.
// code written in C++
#include<iostream>
using namespace std;
int main(){
cout << "Hello World!";
return 0;
} | // code written in Java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
} | 65,203 |
What is the default access modifier for members of a class in Java? | The default access modifier for members of a class in Java is `private`. | 65,250 |
Illustrate the usage of a while loop in Java. | int number = 5;
while (number > 0) {
System.out.println("Number: " + number);
number--;
} | 65,298 |
Create a Java class that contains two methods which take two integers as parameters and returns their sum as the result. | public class Sum {
public static int sumInts(int a, int b) {
return a + b;
}
public static double sumDoubles(double a, double b) {
return a + b;
}
} | 65,301 |
Rewrite the following code snippet to an equivalent code in Python.
int i = 0;
while (i < 10)
{
System.out.println(i);
i++;
} | i = 0
while i < 10:
print(i)
i += 1 | 65,326 |
Write a Java program for encrypting the text "Hello World!" using the Caesar Cipher. | public class CaesarCipher
{
// Encrypts text using a shift od "s"
public static StringBuffer encrypt(String text, int s)
{
StringBuffer result= new StringBuffer();
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
... | 65,433 |
Please debug the following Java code to calculate the average grade of 4 students.
public class Main
{
public static void main (String[] args)
{
int student1 = 77;
int student2 = 85;
int student3 = 90;
int student4 = 96;
int totalScore = 0;
totalScore += student... | public class Main
{
public static void main (String[] args)
{
int student1 = 77;
int student2 = 85;
int student3 = 90;
int student4 = 96;
int totalScore = 0;
totalScore += student1;
totalScore += student2;
totalScore += student3;
totalSco... | 65,448 |
Name the Java abstract class used for user-defined exceptions | The Java abstract class used for user-defined exceptions is called "Throwable". | 65,483 |
Write a while loop in Java to print all even numbers between 0 and 20 | int number = 0;
while(number <= 20){
if(number % 2 == 0){
System.out.println(number);
}
number++;
} | 65,484 |
Provide an example of a valid linked list in Java | class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head; ... | 65,485 |
Design a solution for the Towers of Hanoi problem using Java. | public class TowersOfHanoi {
public static void towersOfHanoi(int n, char from_rod,
char to_rod, char aux_rod)
{
if (n == 1) {
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towersOfHa... | 65,499 |
Create a method in Java to print square of a given number. | public static void printSquare(int number) {
int result = number * number;
System.out.println("Square of " + number + " is: " + result);
} | 65,521 |
Write Javascript code to create a timeout to set a message after 5 seconds. | setTimeout(() => {
console.log('This is the message after 5 seconds');
}, 5000); | 65,527 |
Explain what a constructor is in Java. | A constructor in Java is a special type of method that is used to initialize an object when it is created. A constructor is invoked automatically when an instance of an object is created and is usually used to set initial values for the object’s instance variables. Constructors can also be overloaded to accept differen... | 65,620 |
Write a Java program to create a calculator using Switch statement. | import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter two numbers: ");
int firstNumber = sc.nextInt();
int secondNumber = sc.nextInt();
System.out.println("Please e... | 65,678 |
Write a Java method which will print the Fibonacci sequence based on a given number. | public void fibonacciSeries(int number)
{
int prev = 0;
int current = 1;
System.out.print("Fibonacci Series of "+number+" numbers:");
for (int i = 1; i <= number; i++)
{
System.out.print(prev+" ");
int sum = prev + current;
prev... | 65,700 |
Design a class in Java to represent a person's contact information like name, phone number and email address. | //class definition
public class Contact {
private String name;
private String phoneNumber;
private String email;
public Contact(String name, String phoneNumber, String email) {
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
}
//getters and setters
public String getNa... | 65,703 |
Write a Java code snippet to take input from the user and print the result. | Scanner input = new Scanner(System.in);
int number = input.nextInt();
System.out.println(number); | 65,715 |
Transform the following C code into Java code.
int array[100];
int i, sum = 0;
for (i = 0; i < 100; i++)
sum += array[i]; | int[] array = new int[100];
int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
} | 65,718 |
Adapt the following Java program to print the smallest number from an array of numbers. | public class Smallest_Number {
public static void main(String[] args) {
int arr[] = {10, 15, 5, 20};
int smallest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
System.out.println(smalle... | 65,723 |
Write a Java program for removing all white spaces from a given string. | public class RemoveSpace {
public static String removeSpace(String str) {
return str.replaceAll("\\s","");
}
public static void main (String[] args) {
String str = "Hello World!";
str = removeSpace(str);
System.out.println(str);
}
} | 65,737 |
Create a program in Java that finds the maximum element in an array. | public static int getMaxElement(int[] arr) {
int max = Integer.MIN_VALUE;
for (int el : arr) {
if (el > max)
max = el;
}
return max;
} | 65,760 |
Create a program in Java that calculates the average of two test scores.
test1 = 85
test2 = 90 | public static double average(int test1, int test2){
double avg = (test1+test2)/2;
return avg;
} | 65,797 |
Write code in Java to calculate the minimum number of coins needed to make change for a given amount.
Coin denominations: [1, 5, 10, 25]
Amount: 27 | public int calculateCoins(int amount, int[] array){
int coinsNeeded = 0;
for (int i = array.length - 1; i >= 0; i--){
// Find the largest denomination
// which is smaller than amount
while (amount >= array[i]){
amount = amount - array[i];
coinsNe... | 65,816 |
Generate a sorting algorithm written in Java that sorts integers in ascending order. | public static int[] sortIntsAscending(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
... | 65,829 |
Demonstrate how to use an if-else block to control the execution sequence of a program. | Using an if-else block to control execution sequence involves using if-else statements to check a given condition. If the condition is true, the code inside the if statement is executed, otherwise, the code inside the else statement is executed. For example, if a variable called "x" is declared with a value of 3, the f... | 65,831 |
How can you use the modulo operator to print even numbers in a loop? | The modulo operator can be used to print even numbers in a loop by using an IF statement to check if the remainder of a number divided by two is zero. If the condition is true, the even number is printed. For example, the following code will print all even numbers from 1 to 10:
for (int i = 1; i <= 10; i++){
if (i... | 65,833 |
Make a GUI app in Java to add two numbers together. | import java.awt.*;
import javax.swing.*;
public class AddTwoNumbersGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("Adding two numbers");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Containe... | 65,858 |
Generate a Java program that creates a class Student with attributes name and age, and a constructor to initialize the attributes. | public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
} | 65,884 |
Come up with a Java program that checks if one string is a substring of another. | public static boolean isSubstring(String s, String x) {
int i = 0, j = 0;
while (i < s.length() && j < x.length()) {
if (s.charAt(i) == x.charAt(j)) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == x.length()) {
retur... | 65,889 |
Assign the value 2 to the variable x in Java. | int x = 2; | 65,937 |
Create a Java program that asks the user to input a string and prints out its upper-case version. | import java.util.Scanner;
class UpperCaseString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string: ");
String input = scanner.nextLine();
System.out.println("The upper-case version of this ... | 65,972 |
Write a Java program to iterate through a HashMap. | import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main (String[] args)
{
// Creating a HashMap
Map<String, Integer> hash_map = new HashMap<String, Integer>();
// Mapping int values to string keys
hash_map.put("Geeks", 10);
... | 66,008 |
Construct an array of integers from 1 to 10 in Javascript | let myArray = [1,2,3,4,5,6,7,8,9,10]; | 66,042 |
Implement a Java program that reads five integers and prints their sum.
5, 8, 12, 1, 4 | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
// Read the integers
for (int i = 0; i < 5; i++) {
int x = sc.nextInt();
sum += x;
}
System.out.println("The sum is " + sum);
}
} | 66,051 |
Create a class in Java that prints "Hello World!" | class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
} | 66,066 |
Given a number as an input, write a code in Java to check if it is an Armstrong number.
Number: 153 | public class ArmstrongNumber {
public static boolean armstrongNumber(int number)
{
int result = 0, originalNumber, remainder;
originalNumber = number;
// Check if the number is Armstrong number
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
... | 66,069 |
Write an algorithm in Java that finds the maximum value in an array.
int[] arr = { 4, 9, 3, 6, 1 }; | int maxVal(int[] arr) {
int maxVal = arr[0];
for (int i=1; i<arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
} | 66,086 |
Create a program in Java that finds the average of a given array.
int[] arr = {3, 4, 5, 6}; | public static double findAvg(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double avg = (double)sum / (double)arr.length;
return avg;
} | 66,088 |
Create a Java program to find the sum of the following array [1,2,3,4,5]. | public class Sum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
// Compute sum of array elements
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
// Print sum
System.out.println("Sum of given array elements is: " + sum);
}
} | 66,089 |
Create a Java programme that accepts two strings and returns the length of the longest string.
String string1 = "Hello";
String string2 = "World!"; | int longest = Math.max(string1.length(), string2.length());
System.out.println("Longest string length is "+ longest); | 66,116 |
Design a class in Java called 'Student' which contains student's information such as name, age, etc. | public class Student {
private String name;
private int age;
private boolean status;
public Student(String name, int age, boolean status) {
this.name = name;
this.age = age;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
thi... | 66,132 |
Write a method in Java which displays a printing pattern like shown below.
x
xx
xxx
xxxx | public static void printPattern(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("x");
}
System.out.println();
}
} | 66,133 |
Debug the following code to print all the elements of an array.
int[] arr = {1,2,3,4,5};
for (int i = 0; i < arr.len; i++){
System.out.println(arr[i]);
} | int[] arr = {1,2,3,4,5};
for (int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
} | 66,150 |
Add a feature to the given code to print the name of the largest number in an array.
int[] arr = {5,3,7,2,4};
int largest = arr[0];
for (int i = 1; i < arr.length; i++){
if(arr[i] > largest){
largest = arr[i];
}
} | int[] arr = {5,3,7,2,4};
int largest = arr[0];
String name;
for (int i = 1; i < arr.length; i++){
if(arr[i] > largest){
largest = arr[i];
name = Integer.toString(arr[i]);
}
}
System.out.println("The largest number is " + name); | 66,155 |
How would you form an argument in Java? | A Java argument is specified either at the command line while running a program, or within the code of a method. When running a program, the argument is specified after typing the program name followed by a space. The argument can be of any data type, such as a string, an integer, a double, and so on.
Within a method,... | 66,172 |
Design a public Java API to generate a cookie. | public interface CookieGenerator {
public String generateCookie();
} | 66,198 |
Write a Java program to find all combinations of two numbers in an array that add up to a given sum.
Array: [2, 7, 3, 5]
Sum: 10 | public static List<List<Integer>> findSumPairs(int arr[], int sum) {
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int target = sum - arr[i];
if (map.containsKey(target)) {
result.add(Arrays.a... | 66,211 |
How can you access the fourth element of a linked list in Java? | The fourth element of a linked list in Java can be accessed by traversing the list from the start node three times, where each traverse proceeds one node at a time. The fourth node can be accessed by calling getData() on the traversed node. | 66,213 |
Using Java, write a program that calculates the average of 5 numbers entered by the user.
2, 4, 6, 8, 10 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numList = new int[5];
int sum = 0;
for(int i=0;i<numList.length;i++){
System.out.println("Enter number "+(i+1));
... | 66,221 |
Write a Java command line program to input a string and print out the reversed string. | import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string : ");
String inputString = scanner.nextLine();
String reversedString = "";
for(int i=inputString.length()-1; i>=0; i--) {
... | 66,258 |
Read the following command line arguments in Java and print out the values.
-v -f -d input.txt | String[] args = {"-v", "-f", "-d", "input.txt"};
for (String arg : args) {
System.out.println(arg);
} | 66,293 |
What is the difference between compile-time and run-time errors? | Compile-time errors occur when code does not conform to the syntax specified by the programming language, and usually prevent the code from being executed. Run-time errors occur when code is syntactically correct, but there are still problems executing the code. Run-time errors typically occur at the point where code i... | 66,295 |
Create multiple classes in Java with the provided input.
class Player {
String name;
int age;
String club;
String position; | class Player {
String name;
int age;
String club;
String position;
// Constructors
public Player(String name, int age, String club, String position) {
this.name = name;
this.age = age;
this.club = club;
this.position = position;
}
// Getters and Set... | 66,364 |
Write a Java code to find the maximum of two numbers a and b.
int a = 3;
int b = 4; | int max;
if (a > b) {
max = a;
} else {
max = b;
} | 66,371 |
Write a Javascript code to remove all duplicate values from an array, arr.
let arr = [1,2,2,3,4,4,5]; | let uniqueValues = [...new Set(arr)];
console.log(uniqueValues); | 66,376 |
In Java, how do I create an array of integers from a given array of strings with integer values? | String[] strArray = {"1", "2", "3", "4"};
int[] intArray = Arrays.stream(strArray)
.mapToInt(Integer::parseInt)
.toArray(); | 66,382 |
Create a Java program that returns the minimum value in an array of integers. | public static int minValue(int[] arr) {
int minValue = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < minValue) {
minValue = arr[i];
}
}
return minValue;
} | 66,385 |
Sort elements of an array in descending order in Java. | public static int[] sortDesc(int[] nums) {
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));
return nums;
} | 66,390 |
Write a Java class that can be used to store and access a large dictionary.
Large dictionary with 10000 words | import java.util.HashMap;
public class Dictionary {
private HashMap<String, String> dictionary;
public Dictionary() {
this.dictionary = new HashMap<>();
}
public void addWord(String word, String definition) {
dictionary.put(word, definition);
}
public String getDefinitio... | 66,397 |
Write an if-else statement in Java that prints "red" if a variable "color" is set to "red" and prints "blue" otherwise. | if (color == "red") {
System.out.println("red");
} else {
System.out.println("blue");
} | 66,413 |
Define four classes in Java that form a hierarchy of fruit. | // Base class
public abstract class Fruit {
private String color;
public Fruit(String color) {
this.color = color;
}
public abstract double getWeight();
}
// Inheriting class
public class Apple extends Fruit {
private double weight;
public Apple(String color, double wei... | 66,416 |
Create a class in Java called 'Student' which has the following attributes: firstname, lastname, age, gender. | public class Student {
private String firstname;
private String lastname;
private int age;
private String gender;
public Student(String firstname, String lastname, int age, String gender) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.gender = gen... | 66,513 |
Create a new method in a given Java class named 'Person' which prints a greeting based on the firstname and lastname given.
John Doe | public void printGreeting(String firstname, String lastname) {
System.out.println("Hello, " + firstname + " " + lastname + "!");
} | 66,515 |
Write a Java program that takes an array of integers and returns the number of zeros in the array.
[4, 0, 2, 4, 0, 0] | public static int countZeroes(int[] data) {
int count = 0;
for (int i : data) {
if (i == 0) {
count += 1;
}
}
return count;
} | 66,540 |
How can you implement a Bubble Sort algorithm in Java? | public class BubbleSort {
public static void sort(int[] arr) {
int n = arr.length;
int temp;
for(int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j+1]) {
// Swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
} | 66,546 |
Create a class structure in Java for an Employee object. | public class Employee {
private int id;
private String name;
private double salary;
// default constructor
public Employee() {
}
// parameterized constructor
public Employee(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
t... | 66,555 |
Create a class in Java that stores name, age, and height as input fields. | public class Person {
private String name;
private int age;
private double height;
public Person(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {... | 66,578 |
Generate a class for a Student object in Java. | public class Student {
private String name;
private String id;
private String email;
private String major;
public Student(String name, String id, String email, String major) {
this.name = name;
this.id = id;
this.email = email;
this.major = major;
}
public String getName() {
return name;
}
publi... | 66,595 |
Create a class in Java called 'Circle' that stores information about a circle's radius and calculate the area. | public class Circle {
public double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
} | 66,601 |
Translate this piece of C++ code into Java.
int num = 10;
for (int i = 0; i < num; i++) {
num++;
} | int num = 10;
for (int i = 0; i < num; i++) {
num++;
}
// translated to Java:
int num = 10;
for (int i = 0; i < num; i++) {
num++;
} | 66,605 |
Using Java, write a program to determine if a given word is a palindrome.
word = "racecar" | boolean isPalindrome = true;
for (int i = 0; i < word.length()/2; i++ ){
if (word.charAt(i) != word.charAt(word.length()-i-1)){
isPalindrome = false;
break;
}
} | 66,620 |
Create a Java program which calculates the area of a circle. | public class AreaCalculator {
public static final double PI = 3.14159;
public static double calculateArea(double radius) {
return PI * radius * radius;
}
public static void main(String[] args) {
System.out.println(calculateArea(10));
}
} | 66,667 |
Specify the platform and the environment variables needed to run a Java program. | The platform dependent environment variables needed to run a Java program on any platform are:
1. JAVA_HOME: This variable stores the location of JDK.
2. PATH: This variable stores the path to the executables.
3. CLASSPATH: This variable contains the path to the Java classes.
4. JRE_HOME: This variable stores the loca... | 66,670 |
Name two differences between Strings and StringBuffer in Java. | The two major differences between String and StringBuffer in Java are:
1. String objects are immutable in nature whereas StringBuffer objects are mutable.
2. String objects are created using "String Literal" whereas StringBuffer objects are created using the "new" keyword. | 66,671 |
Describe the differences between List, ArrayList, and Vector in Java. | The main differences between List, ArrayList, and Vector are their memory utilization, synchronization, and thread safety . List is an interface that is the parent class of ArrayList and Vector. ArrayList is an unsynchronized collection, making it faster but not thread safe and Vector is a synchronized collection, maki... | 66,675 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.