instruction
stringlengths
25
5.05k
output
stringlengths
4
8.53k
__index_level_0__
int64
34
78.2k
Create a Java program that prints a 10x10 multiplication table.
class MultiplicationTable { public static void main(String[] args) { System.out.print(" "); for(int i=1; i<=10; i++) System.out.printf("%4d", i); System.out.println(); for(int i=1; i<=10; i++) { System.out.print(i + " "); for(int j=1; j<=10; j++) System.out.printf("%4d", i ...
72,135
Explain the main differences between Java and Python.
The main differences between Java and Python include speed of development, execution speed, type safety, readability and syntax ease, standard libraries, and code scalability. Java is more popular in enterprise applications and is generally faster to develop than Python because of its statically typed language. Java ha...
72,139
Write a Java statement that takes a string as an argument and prints it out. String s = "Hello World!";
System.out.println(s);
72,148
Write a Java program to output the first ten numbers of the Fibonacci sequence.
class Fibonacci { public void printFibonacciNumbers(int n) { int first = 0; int second = 1; System.out.print(first + " " + second); for (int i = 2; i < n; i++) { int third = first + second; System.out.print(" "+third); first = second; second = third; } ...
72,152
Construct a switch statement to check if a month name is valid.
// switch statement to check if a month name is valid switch (month) { case "January": case "February": case "March": case "April": case "May": case "June": case "July": case "August": case "September": case "October": case "November": case "December": System.out...
72,160
Create a Spring boot program to find the area of a triangle.
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { // Function to calculate the area of triangle public static double calculateArea(int a, int b, int c) { double s = (a + b + c) / 2; double area = Math.sqrt(s * (s - a) * (s...
72,162
Create a Java program that removes duplicate elements from an array. int arr[] = {12, 11, 12, 11, 13, 11};
import java.util.HashSet; public class RemoveDuplicates { public static int[] removeDuplicates(int arr[]) { // HashSet for removing duplicates HashSet<Integer> set = new HashSet<>(); // adding elements to HashSet for(int i=0; i<arr.length; i++) set.add(arr[i]); ...
72,253
Explain the concept of classes and objects in Java.
Classes in Java are user-defined templates for creating objects. A class specifies the data and behavior associated with any objects created from it. An object is an instance of a class which contains its own set of attributes and methods. Objects can interact with each other’s attributes and methods. Classes and objec...
72,308
Write a Java method to decide if one point is inside a given rectangle or not.
public static boolean isPointInsideRectangle(Point p, Rectangle r) { return (p.getX() <= r.getMaxX() && p.getX() >= r.getMinX() && p.getY() <= r.getMaxY() && p.getY() >= r.getMinY()); }
72,312
Output "Hello World!" using Java.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
72,344
Write a Java code snippet to swap two given values. int a = 10; int b = 20;
int temp = a; a = b; b = temp;
72,352
Write a C# program to take a given number and print it in words. int n = 1234
int n = 1234; String[] ones = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; String[] teens = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; String[] tens = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", ...
72,367
Create a class in Java that stores a student's ID and name.
public class Student { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } }
72,378
In Java, how do you make a method that takes a number and displays its square?
public static void displaySquare(int num){ System.out.println(num*num); }
72,395
In the given Java program replace the line number 3 with a line that outputs the remainder of dividing 10 by 3. public class Main { public static void main(String[] args) { // Code to be replaced } }
public class Main { public static void main(String[] args) { System.out.println(10 % 3); } }
72,431
Create a class in Java with private variables, getter and setter method, and constructor.
public class MyClass { private int variable1; private int variable2; public MyClass(int variable1, int variable2) { this.variable1 = variable1; this.variable2 = variable2; } public int getVariable1() { return variable1; } public void setVariable1(int va...
72,435
Describe how multithreading works in Java.
Multithreading in Java is a process by which multiple threads can exist within the context of a single program and run concurrently. This allows for multiple processing tasks to be accomplished at the same time and makes the most of your available processing power. In a multithreaded application, threads can share obje...
72,439
Write a Java program for sorting a given list of numbers in descending order. unsortedList = [7, 6, 5, 4, 3, 2, 1]
import java.util.Arrays; public class SortList { public static void main(String[] args) { int unsortedList[] = {7, 6, 5, 4, 3, 2, 1}; Arrays.sort(unsortedList); int n = unsortedList.length; for (int i=n-1; i>=0; i--) System.out.print(unsortedList[i]+" "); ...
72,447
Modify the following Java code to print the second element in a given array. int[] arr = {1, 2, 3, 4, 5};
int[] arr = {1, 2, 3, 4, 5}; System.out.println(arr[1]);
72,457
Create a Java method that takes a decimal number as an argument and returns its binary equivalent.
public static String decToBinary(int n) { String s=""; while(n > 0) { int a = n % 2; s = a + s; n = n / 2; } return s; }
72,461
What is the name of the method used in Java to compare two strings?
The method used in Java to compare two strings is the .equals() method.
72,465
Write a Java program to create a class for a circle, with a parameter for the radius, and methods for calculating the area and circumference of a circle.
public class Circle { double radius; public Circle(double r){ this.radius = r; } public double area(){ return (Math.PI * Math.pow(this.radius, 2)); } public double circumference(){ return (2 * Math.PI * this.radius); } }
72,469
How to check if a given number is a multiple of 10 in Java?
In Java, the best way to check if a given number is a multiple of 10 is to use the modulo operator (%). The modulo operator (x % y) will return 0 if x is a multiple of y. Therefore, if (n % 10) == 0, then n is a multiple of 10.
72,472
Design a Java method that takes an integer as an argument and prints its negative equivalent. int x = 5;
public static void printNegativeNumber(int x) { System.out.println(-x); } printNegativeNumber(x); // -5
72,485
Differentiate the methods of machine learning and explain the differences.
There are three main methods of machine learning: supervised learning, unsupervised learning, and reinforcement learning. In supervised learning, the model is trained using labeled data, that is, data that has its output (or target) value given to the model. Unsupervised learning models learn by extracting patterns fro...
72,503
Write a Java program to find all pairs of integers from an array whose sum equals a given number.
public static List<int[]> findSumPairs(int[] arr, int target) { List<int[]> pairs = new ArrayList<>(); Map<Integer, Integer> numFreqMap = new HashMap<>(); for (int value : arr) { numFreqMap.put(value, numFreqMap.getOrDefault(value, 0) + 1); } for (int value : arr) { int target...
72,538
Write a stack class in Java.
public class Stack { private int[] stackArray; private int maxSize; private int top; public Stack(int size) { maxSize = size; stackArray = new int[maxSize]; top = -1; } public void push(int item) { stackArray[++top] = item; } public int pop()...
72,550
Construct a program in Java to sort an array of String objects.
public class StringSort { public static void sortStringArray(String[] arr) { // Sorting strings Arrays.sort(arr); // Displaying the strings after sorting System.out.println("Strings in sorted order: "); for (int i = 0; i < arr.length; i++) System...
72,552
Describe the different thread states in Java programming.
In Java, threads can be in one of the following states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED. The NEW state means that the thread has been created but not yet started. RUNNABLE means that the thread is running. BLOCKED means that the thread is waiting to acquire a lock. WAITING and TIMED_WAITING...
72,557
List the types of inheritance supported in Java.
In Java, there are four types of inheritance supported: single inheritance, multiple inheritance, hierarchical inheritance, and socioeconomic inheritance. Single inheritance means a class extends only one class. Multiple inheritance is when a subclass extends multiple superclasses. Hierarchical inheritance is when a cl...
72,559
Create a Java program for finding the largest number among three integers.
public class LargestNumber { public static int getLargestNumber(int num1, int num2, int num3) { int greater; if( num1 > num2 && num1 > num3) greater = num1; else if( num2 > num1 && num2 > num3) greater = num2; else greater = num3; ...
72,574
Print the duplicated items in an array of integers. array: [1, 2, 3, 2, 5, 1]
""" Print the duplicated items in an array of integers """ public class DuplicateItems { public static void main(String[] args) { int [] array = {1, 2, 3, 2, 5, 1}; List<Integer> duplicates = new ArrayList<Integer>(); for(int i = 0; i < array.length-1; i++){ for(i...
72,631
Write a code in Java to print out the power of two of the given number. Number: 4
""" Write a code in Java to print out the power of two of the given number """ public class TwoPower { public static void main(String[] args) { int number = 4; double res = Math.pow(2,number); System.out.println("2 to the power of " + number + " is " + res); } }
72,632
Evaluate the expression 3^2 + 5%2.
""" Evaluate the expression 3^2 + 5%2 """ int result = 3^2 + 5%2; System.out.println("Result: "+ result); // Output: Result: 8
72,634
Given an array of numbers, find the index of the first occurrence of a given number in Java.
public class FindIndex { public static int findIndex(int[] arr, int n) { int i; for (i = 0; i < arr.length; i++) { if (arr[i] == n) break; } if (i < arr.length) return i; else return -1; } }
72,680
How is a 2D array declared and initialized in Java?
int[][] array 2D = new int[n][m]; //where n is the number of rows and m is the number of columns. //You can also create a 2D array by initializing elements with curly brackets, for example int[][] array2D = {{1,2,3},{4,5,6}};
72,688
Gather the source code of a web page using a Java program. String url = "https://www.example.com";
try { URL page = new URL(url); URLConnection conn = page.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()) ); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); ...
72,702
Which language is used to develop applications for the Android platform?
The official language for developing applications for the Android platform is Java. Java is an object-oriented programming language, which allows developers to create robust and reliable applications for Android devices.
72,712
Write a code in Java for creating an instance of an interface.
MyInterface myInterface = new MyInterface() { @Override public void myMethod() { // Implement your code here } };
72,733
Create a Java class for representing a student object.
public class Student { private String id; private String name; private int age; public Student(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id)...
72,799
Create a Java program to print out the multiplication table for the first 10 numbers
public class MultiplicationTable { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
72,819
Create a Java program to compute the volume of a cube.
public class CubeVolume { public static void main(String[] args) { double sideLenght = 10; double volume; volume = sideLenght * sideLenght * sideLenght; System.out.println("Volume of a cube with side lenght "+ sideLenght +" is: " + volume); } }
72,844
Write a Java program that creates two arrays and prints out the difference in number of elements between them. int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {1, 2, 3};
public class ArraySizeDiff { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {1, 2, 3}; int diff = arr1.length - arr2.length; System.out.println("Difference in number of elements between the two arrays is: " + diff); } }
72,870
Calculate the following expression using Java: (3^3+11) × (3+3)
int result = (int)Math.pow(3, 3) + 11 * (3 + 3); // result = 144
72,878
Create a java program that checks if a given string has any special characters String str = "This is a string!"
public class CheckSpecialChar { public static void main(String[] args) { String str = "This is a string!"; boolean flag = false; String specialChar = "[^a-zA-Z0-9]"; if(str.matches(specialChar)) { flag = true; } System.out.println("Does the string...
72,889
Create two classes 'Circle' and 'Rectangle' in Java which print the circumference and area of their respective shapes.
class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public double getCircumference() { return 2 * Math.PI * this.radius; } public double getArea() { return Math.PI * this.radius * this.radius; } } class Rectangle { private double width; private double length...
72,894
Generate a Java program to sort an array of n elements in ascending order
public static void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp =...
72,939
Using Java, create a program that takes a list of strings, and returns the longest one. strings = ["hello", "world", "this", "is", "a", "test"]
public static String getLongestString(String[] strings) { int maxLength = 0; String longestString = null; for (String s: strings) { if (s.length() > maxLength) { maxLength = s.length(); longestString = s; } } return longestString; }
72,952
Using Java, build a program that will convert a given number from one base to another.
public static int convertBase(int num, int fromBase, int toBase) { int result = 0; int power = 1; while (num > 0) { result += (num % toBase) * power; power *= fromBase; num /= toBase; } return result; }
72,958
Why is using the+= operator more efficient than using a+=b on strings in Java?
Using the += operator is more efficient on strings than using a+=b in Java because += operator creates only one string object in memory, whereas a+=b creates a new string every time and requires two string objects. This means that using += operator for strings is faster and uses less memory than using a+=b. This is bec...
72,964
Create a Java class called Student that contains a first name, last name and age.
public class Student { private String firstName; private String lastName; private int age; public Student(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { ...
72,965
Create a Java class which sorts the given array of numbers. [9, 2, 4, 3, 6, 1]
class ArraySort { 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_index = i; for (int j = i+1; j < n...
72,989
Write a Java program to remove n characters from a given string, starting from a specified position. str = "This is a sample string" n = 5 pos = 8
public static String removeCharAt(String s, int pos, int n) { return s.substring(0, pos) + s.substring(pos + n); } // Driver Code public static void main(String[] args) { String str = "This is a sample string"; int n = 5; int pos = 8; System.ou...
73,034
Write a Java program to print all the Armstrong numbers between 100 to 500. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the total number of digits.
public class ArmstrongNumbers { public static void main(String[] args) { int min = 100; int max = 500; for (int number = min; number <= max; number++) { int digits = 0; int result = 0; int originalNumber = number; while (originalNumber ...
73,144
Write a Java code to create a thread and process the tasks in separate threads.
public class Main { public static void main(String[] args) { Thread thread1 = new Thread(new Runnable(){ public void run(){ //task 1 } }); Thread thread2 = new Thread(new Runnable(){ public void run(){ //task 2 ...
73,150
Create a JavaFX program that allows a user to move a square shape in 3 different directions using the arrow keys.
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class MoveSquare extends Application { public static void main(String[] args)...
73,166
Using Javascript, create an object that has a property of message with a value of "Hello, World"
let obj = { message: "Hello, World" }
73,177
Create a method in Java that takes two integers and finds the maximum of them.
public static int findMax(int num1, int num2) { return (num1 > num2) ? num1 : num2; }
73,178
Create a Java method to interpret a given string into an integer.
public static int stringToInteger(String s) { int result = 0; int power = 0; for (int i = s.length() - 1; i >= 0; i--) { char ch = s.charAt(i); result += (ch - '0') * Math.pow(10, power); power++; } return result; }
73,187
Create a Java class with an empty constructor and a parameterized constructor
public class TestConstructor { public TestConstructor() { } public TestConstructor(int n) { // code to run when constructor with parameter is called } }
73,189
Write a Java program that takes an array of integers and prints the numbers that are divisible by 5 [10, 20, 25, 15]
// Create the array of integers int[] numbers = {10, 20, 25, 15}; // Iterate over array and print numbers divisible by 5 for (int number : numbers) { if (number % 5 == 0) { System.out.println(number); } } // Output: 10 20 25
73,192
Implement a data structure in Java that implements a stack with the following methods: 'push', 'pop', 'peek', and 'isEmpty'.
import java.util.*; public class StackImplementation { private Stack<Integer> stack; public StackImplementation() { stack = new Stack<>(); } public void push(int x) { stack.push(x); } public int pop() { if (stack.isEmpty()) { System.out.println("Stac...
73,203
Write a method to implement binary search using Java.
public static int binarySearch(int[] array, int x) { int low = 0, high = array.length - 1; while (low <= high) { int mid = (low + high) / 2; if (array[mid] < x) low = mid + 1; else if (array[mid] > x) high = mid...
73,212
Write a RabbitMQ consumer in Java to listen to a particular queue.
import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DeliverCallback; public class Consumer { public static void main(String[] args) throws Exception { // establish a connection to the RabbitMQ broker ConnectionFa...
73,243
For a given programming language, list the data types supported by that language.
In Java, the supported data types include primitive data types like int, float, char, as well as non-primitive types such as String, Array, List, Set, and Map.
73,287
Generate a random 9-digit id in Java.
import java.util.Random; public class Example { public static void main(String[] args) { Random random = new Random(); int random_number = 1000000000 + random.nextInt(900000000); System.out.println(random_number); } }
73,290
Write the output for the following Java program. public class OddNumber { public static void main(String[] args) { for(int i=10; i<20; i++) { if(i % 2 == 1) { System.out.println(i); } } } }
11 13 15 17 19
73,329
Rewrite the following code snippet (written in Java), such that the same purpose is accomplished but with fewer lines of code. public static void printList(List<String> list) { for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }
public static void printList(List<String> list){ list.forEach(s -> System.out.println(s)); }
73,342
Write a Java code snippet to check whether or not a number is a prime.
public static boolean isPrime(int number) { if (number == 2 || number == 3) return true; if (number % 2 == 0 || number % 3 == 0) return false; int sqrtN = (int)Math.sqrt(number) + 1; for (int i = 6; i <= sqrtN; i += 6) { if (number % (i - 1) == 0 || number % (i + 1) == 0) retur...
73,346
Write a Java program to print the elements (i, j) of a two dimensional array. int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) System.out.print(matrix[i][j] + " "); System.out.println(); }
73,354
Compile a given Java program. A java program containing the following lines class Sample { public static void main(String args[]) { System.out.println("Hello World"); } }
javac Sample.java
73,368
Edit the following Java code so that it will output the length of a string String name = "John"
String name = "John"; System.out.println("Length of string is: " + name.length());
73,398
Create a quicksort alogorithm in the following language Java
import java.util.ArrayList; public class Qsort { public static int partition(ArrayList<Integer> array, int low, int high) { int pivot = array.get(high); int i = low-1; for (int j=low; j<high; j++) { if (array.get(j) < pivot) { i++; int temp = arr...
73,430
What is the purpose of Java virtual machine?
The purpose of the Java virtual machine (JVM) is to provide a runtime environment for Java applications, in which programs are able to run independently of the underlying operating system. It is responsible for providing a secure and portable environment for the Java program's execution, as well as for providing severa...
73,454
Edit the following code to make the loop run for 10 iterations. for (int i = 0; i < 5; i++) { System.out.println(i); }
for (int i = 0; i < 10; i++) { System.out.println(i); }
73,482
What kind of data structure is used for a queue in Java?
A queue in Java is typically implemented using a linked list or an array.
73,485
Debug this Java code and explain what was wrong. public static int add(int a, int b){ int c = a b; return c; }
The code contained a syntax error. In the second line of the code, the operator being used was "b" instead of "+". The correct line should be "int c = a + b;". This error was causing the program to return the wrong value, as it was attempting to perform the wrong calculation.
73,533
Add a class "MyClass" to the given Java code and then create two objects for that class. public class Demo { public static void main(String[] args) { } }
public class Demo { public static void main(String[] args) { MyClass m1 = new MyClass(); MyClass m2 = new MyClass(); } } class MyClass { }
73,566
Describe the purpose of an iterator class in Java.
An iterator class in Java is used to traverse through a collection to access its elements. It allows for the convenient looping and retrieval of elements from the collection in an orderly fashion.
73,568
Explain how to use a break statement in a for loop in Java.
The break statement can be used to prematurely exit a for loop. The break statement is placed within the loop and causes an immediate exit from the loop once it is reached. This can be useful when a certain condition must be met before the loop should continue to execute.
73,571
Create a class in Java for a student and define variables for name, date of birth and grade.
public class Student { private String name; private Date dob; private int grade; public Student(String name, Date dob, int grade) { this.name = name; this.dob = dob; this.grade = grade; } // Additional methods/Getters and Setters }
73,589
You need to generate a Javascript program that prints "Hello World".
console.log("Hello World");
73,591
Design a Java program to find the longest increasing sub-sequence of an array.
public static int longestIncreasingSubsequence(int[] arr) { int[] dp = new int[arr.length]; int maxLength = 1; dp[0] = 1; for (int i=1; i<arr.length; i++) { int maxVal = 0; for (int j=0; j<i; j++) { if (arr[j] < arr[i] && dp[j] > maxVal) { maxVal = dp[j]; } ...
73,592
Write a java code to accept a student name and display a greeting.
import java.util.Scanner; public class GreetStudent { public static void main(String[] args) { // Create a Scanner object Scanner scanner = new Scanner(System.in); // Accept a student name System.out.println("Please enter student name:"); String studentName = scanner.next...
73,613
Write a Javascript code to add four numbers and print the result. numbers = [1, 2, 3, 4]
let numbers = [1, 2, 3, 4]; let result = numbers.reduce((a, b) => a + b); console.log("Result: " + result);
73,616
Generate a code in Java for sorting an array using Mergesort.
public static void sortMerge (int [] array) { //Array must have more than one element if (array.length > 1) { int len = array.length; //Split vector into two halves int mid = len/2; int left [] = Arrays.copyOfRange (array, 0, mid); int right [] = Arrays....
73,622
Write a script in Java for printing the first n Fibonacci numbers.
public class Fibonacci { static int fib(int n) { int f[] = new int[n+2]; // 1 extra to handle case, n = 0 int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } retur...
73,624
Generate a Java program to get the maximum number from a given array.
public class MaxNumber { public static int getMaxNumber(int[] arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } }
73,635
Given a string, write a Java program to verify if it is a valid email address.
public static boolean isValidEmail(String email){ String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); }
73,640
Explain how to handle exceptions using try-catch block in Java.
Exceptions can be handled in Java using try-catch blocks. A try-catch block includes a try statement followed by the catch clauses. The try statement defines the code which can throw an exception, and the catch clause defines an exception handler which handles the exception thrown by the try statement. In the catch blo...
73,643
Using Java, create a program to find the maximum sum of a sub-array within a given array.
// Java Code public class MaximumSubArraySum { public static int maxSubArraySum(int[] nums) { int maxSum = Integer.MIN_VALUE; int currentSum = 0; for (int num : nums) { currentSum += num; if (currentSum > maxSum) maxSum = currentSum; if (currentSum < 0) currentSum = 0; } return maxSum; } public static vo...
73,669
Write a Java class to represent a student record with a student_name, grade and score fields.
public class StudentRecord { private String studentName; private int grade; private double score; public StudentRecord(String studentName, int grade, double score) { this.studentName = studentName; this.grade = grade; this.score = score; } public String getStudentName() { return studentName; } public...
73,672
Code a calculation to find the mean of numbers stored in an array in Java. numbers = {1, 2, 3, 4, 5}
public static double mean(int[] numbers) { double sum = 0.0; for (int i = 0; i < numbers.length; i++) sum += numbers[i]; return sum / numbers.length; }
73,684
Create a class in Java called Employee with the following fields (name, ID, department).
class Employee { // Field String name; int id; String department; // Constructor Employee(String name, int id, String department) { this.name = name; this.id = id; this.department = department; } }
73,731
Produce a Java program that converts miles to kilometers. Miles: 10
class MilesToKilometers { public static void main(String[] args) { // Convert miles to kilometers double miles = 10; double kilometers = miles * 1.60934; System.out.println("Miles: " + miles); System.out.println("Kilometers: " + kilometers); } }
73,781
Generate a random 3x3 array using Java.
Random r = new Random(); int[][] arr = new int[3][3]; for (int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++){ arr[i][j] = r.nextInt(); } }
73,795
Construct an if/else statement in Javascript to display a message depending on the value of a variable called "age". let age = 17
if (age < 18) { console.log("You are not old enough to access this page."); } else { console.log("Welcome to the page!"); }
73,798
Code an algorithm in Java to check if a given array contains duplicate elements. arr = [3, 6, 5, 4, 6, 9]
public static boolean checkDuplicates(int[] arr) { Set<Integer> set = new HashSet<>(); for(int number : arr ) { if(!set.add(number)) { return true; } } return false; }
73,809
Compute the sum of the prime numbers from 0 to n using Java. n = 10
public class PrimeSum{ public static int sumOfPrime(int n){ int sum = 0; for(int i=2; i<=n; i++){ if(isPrime(i)) sum += i; } return sum; } private static boolean isPrime(int n){ for(int i=2; i<n; i++){ if(n%i == 0) ...
73,814
debug the following code in Java to list all the prime numbers until 50 class Main { public static void main(String[] args) { for(int i = 0; i < 50; i++) { if (isPrime(i)) { System.out.println(i); } } } static boolean isPrime(int n){ } }
class Main { public static void main(String[] args) { for(int i = 0; i < 50; i++) { if (isPrime(i)) { System.out.println(i); } } } static boolean isPrime(int n){ if (n <= 1) { return false; } for (int i = 2; i < ...
73,817