instruction
stringlengths
25
5.05k
output
stringlengths
4
8.53k
__index_level_0__
int64
34
78.2k
Write a Java program to ask the user to enter a number and then find and print the corresponding Fibonacci number.
public class Fibonacci{ public static int findFibonacci(int n){ if(n == 0){ return 0; } if(n == 1){ return 1; } return findFibonacci(n-1) + findFibonacci(n-2); } public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Enter a number:"); int n = in.next...
73,819
Convert the string "Hello World" to all uppercase in JAVA. String str = "Hello World";
String strUpper = str.toUpperCase(); System.out.println(strUpper); // Prints: HELLO WORLD
73,839
Create a new Java program that prints out all the prime numbers between 2 and 1000.
public class PrimeNumbers { public static void main(String[] args) { System.out.println("Prime numbers between 2 and 1000 are:"); int count; for(int i=2; i<=1000; i++){ count=0; for(int j=2; j<i; j++){ if(i%j==0){ count++; break; } } if(co...
73,847
Create a program in Java to create a simple calculator that has the ability to add, subtract, multiply, and divide numbers.
public class Calculator { // Function to add two numbers public int add(int num1, int num2) { return num1 + num2; } // Function to subtract two numbers public int subtract(int num1, int num2) { return num1 - num2; } // Function to multiply two numbers pub...
73,939
How can we prevent memory leaks in Java?
Memory leaks in Java can be prevented by following certain coding practices. Firstly, it is important to ensure proper object references are maintained, so that objects are not unintentionally retained in memory for long periods of time. Secondly, it is important to be mindful of resource usage, such as closing input/o...
73,946
Develop a Java program that counts the frequency of a given word in a sentence. Input: sentence = "I am learning to code" , word = "code"
public class CountFrequency { static int countFrequency(String sentence, String word) { int frequency = 0; String[] words = sentence.split(" "); for (String w : words) { if (w.equals(word)) frequency++; } return frequency; } ...
73,977
Implement selection sort algorithm to sort an array of integers in Java. arr = [5, 8, 2, 7, 1]
public static void selectionSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int min_idx = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[min_idx]) min_idx = j; } int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } }
74,026
Write a Java statement to declare a string variable, “str”, and initialize it with a value “Good morning!”.
String str = "Good morning!";
74,033
Implement a Java class for a LinkedList.
public class LinkedList { private Node head; // head of the list // linked list Node. // This inner class is made static // so that main() can access it static class Node { int data; Node next; // Constructor Node(int d) { data = d; ...
74,043
Generate a Java program to read two numbers from the user and print their sum.
import java.util.Scanner; public class SumOfTwoNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num1, num2, sum; System.out.print("Enter first number:"); num1 = scanner.nextInt(); System.out.print("Enter second...
74,045
Generate a program in Java that reads two strings and checks if the strings are equal.
public class StringEquality { public static void main(String[] args) { // two strings String s1, s2; s1 = "Hello"; s2 = "Hello"; if (s1.equals(s2)) System.out.println("Strings are equal."); else System.out.println("Strings are not equal."); } }
74,048
Create an algorithm in Java for maximum subarray problem.
public static int maxSubArraySum(int a[]) { int size = a.length; int maxSoFar = Integer.MIN_VALUE, maxEndingHere = 0; for (int i = 0; i < size; i++) { maxEndingHere = maxEndingHere + a[i]; if (maxSoFar < maxEndingHere) maxSoFar = maxEndingHere; if (maxEndi...
74,051
Write a Java code snippet to print out the current system time.
long currentTimeMillis = System.currentTimeMillis(); SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss"); Date resultdate = new Date(currentTimeMillis); System.out.println(sdf.format(resultdate)); //Result: Dec 01,2020 13:55:42
74,081
Design a program to find the sum of all numbers in an array of size 5 int arr[] = {4, 8, 2, 6, 1};
public class SumOfElements { // Function to get sum of all elements. public static int getSum(int[] arr) { int sum = 0; for (int i : arr) sum += i; return sum; } public static void main(String[] args) { int arr[] = { 4, 8, 2, 6, 1 }; ...
74,086
Provide a syntax for an if-else statement in Javascript.
if (condition) { // statements when condition is true } else { // statements when condition is false }
74,100
Create a Java program that takes input from a user and prints it out.
import java.util.Scanner; public class Echo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String line = input.nextLine(); System.out.println(line); } }
74,112
Place the missing code in the following Java program to print "Hello World!". public class HelloWorld { public static void main(String[] args) { ~ } }
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
74,116
Use the Java StringBuilder class to append three strings to a single string. String1: "Hello," String2: " world!" String3: " Have a nice day!"
StringBuilder sb = new StringBuilder(); sb.append("Hello,"); sb.append(" world!"); sb.append(" Have a nice day!"); String finalString = sb.toString();
74,130
Create a Java program that takes in a String and returns a String with the letters of the original String reversed. string = "Hello"
public static String reverseString(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length() - 1; i >= 0; i--) { sb.append(s.charAt(i)); } return sb.toString(); }
74,145
What are the benefits of abstract classes in Java?
Abstract classes in Java provide a way to define and enforce common behavior that is shared between derived classes. They also allow for code reuse as the shared code can be reused by other classes. Furthermore, with the help of abstract classes, one can create a structure for developers to follow and provide a standar...
74,314
Design a Java code to create a method that counts the number of elements in a given array. int[] array = {2, 4, 6, 8}
public static int countArrayElements(int[] input) { int count = 0; for (int element : input) { count++; } return count; } int arraySize = countArrayElements(array); // prints 4
74,317
Given an array of numbers, code a Java code to find out the highest number. int arr[] = {20, 35, -15, 7, 55, 1, -22}
public static int findHighestNumber (int[] numbers) { int highestNumber = Integer.MIN_VALUE; for (int currentNumber : numbers) { highestNumber = Math.max(currentNumber, highestNumber); } return highestNumber; } int highestNumber = findHighestNumber(arr); // prints 55
74,325
Identify the ‘time complexity’ of an algorithm written in Java that calculates average of all elements in a list.
The time complexity of the algorithm is O(n) since it needs to loop through all the elements in the list in order to calculate the average.
74,332
Write Javascript code to select all div elements with the class "container".
let containers = document.querySelectorAll('div.container');
74,347
Create a Java program to output the Fibonacci series upto the given number. Number: 10
public class Fibonacci { public static void main(String[] args) { int num = 10; int first = 0; int second = 1; System.out.println("Fibonacci Series of " + num + " numbers:"); for (int i = 0; i < num; i++) { System.out.print(first + " "); int ...
74,386
Write a Java program that prints a rating out of 10 based on user input. Input value: 7
public class Rating { public static void main (String[] args) { int inputValue = 7; int rating = 0; if (inputValue >= 8) { rating = 10; } else if (inputValue >= 5) { rating = 7; } else { rating = 4; } System.out.println("Rating: " + rating); } }
74,389
Create a Java method that takes two integer arguments and returns their multiplication.
public static int multiply(int a, int b) { return a * b; }
74,395
Using Java, write a method that takes an array of integers and replaces all the negative numbers with 0. int[] arr = {2, 3, -4, 5, 7, -8};
public static int[] replaceNegs(int[] arr) { for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) arr[i] = 0; } return arr; }
74,397
What is Constructor Chaining in Java?
Constructor chaining is a feature in Java that enables a class to call one or more other constructors of the same class in the same order as they appear in the class. This enables code reuse and helps to write a concise and robust constructor.
74,470
Write a Java program to implement Matrix multiplication
public class MatrixMultiplication { public static void main(String []args) { int[][] matrix1 = { {1, 1}, {2, 2} }; int[][] matrix2 = { {1, 1}, {2, 2} }; int rows1 = matrix1.length; int co...
74,498
Write a java program to count the number of characters in a sentence without using a loop. sentence = "This is a simple sentence"
//using 'split()' method String[] words = sentence.split("\\s+"); //split with regular expression int count = 0; for(String word: words){ count += word.length(); } System.out.println("The number of characters in the sentence is : "+count); //using 'replaceAll()' method int count = sentence.replaceAll(" ", "").len...
74,501
Fix the following Java code by replacing the letter "u" with "v". String s1 = "Update";
String s1 = "Update"; String s2 = s1.replace('u','v');
74,531
Create a class in Java called Student with two fields called id and name.
public class Student { int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { ...
74,592
Create a short Java program designed to accept two numbers and find their greatest common divisor (GCD).
public class GCD { public static int getGCD(int x, int y) { // Base case if (x == 0) return y; if (y == 0) return x; // If x is greater if (x > y) return getGCD(x%y, y); return getGCD(x, y%x); } public s...
74,610
Construct a class in Java that creates methods for finding the area and circumference of a circle.
public class Circle { double radius; public Circle(double radius) { this.radius = radius; } public double getArea(){ return Math.PI * Math.pow(radius, 2); } public double getCircumference(){ return 2 * Math.PI * radius; } }
74,614
Write a Java method that checks if a nested integer contains an even number. [1, 2, [3, 4, [7, 8]]]
public static boolean containsEven(List<Object> list) { for (Object obj : list) { if(obj instanceof Integer){ if((Integer)obj % 2 == 0){ return true; } } else if(obj instanceof List<?>){ if (containsEven((Lis...
74,620
Design a class in Java to represent a stack data structure, and implement operations such as push, pop and size.
public class Stack { private int[] arr; private int top; private int capacity; public Stack(int capacity) { this.arr = new int[capacity]; this.top = -1; this.capacity = capacity; } public boolean isFull() { return top == capacity - 1; } public boo...
74,621
Create classes in Java to represent a school and its students.
public class School { private String name; private List<Student> students; //constructor, getters, setters, and other methods public void addStudent(Student student) { students.add(student); } } public class Student { private String name; private int age; //constructor, g...
74,677
Create an algorithm in Java to calculate the average of five numbers.
public static double avgOfFiveNums(int a, int b, int c, int d, int e) { double avg = (a + b + c + d + e) / 5.0; return avg; }
74,690
Create a Java method that takes three integers as parameters and computes their average.
public static double threeIntAvg(int a, int b, int c) { return (a + b + c) / 3.0; }
74,714
Which of the following is a valid way to declare a variable in Java?
int variable; String variable = ""; boolean variable = false;
74,739
Create a Javascript object that stores the number of cats and dogs in a given location.
const pets = { cats: 10, dogs: 12 };
74,745
Create an array in Javascript that contains elements of different datatypes.
let array = [1, "String", true, { key: "value" }, [1,2]];
74,748
Develop a Java program that takes two strings as input and outputs the common characters in both strings. String A: abcde String B: defgh
public class CommonChars { public static void main(String[] args) { String str1 = "abcde"; String str2 = "defgh"; //Loop through both strings for (int i = 0; i < str1.length(); i++) { char ch1 = str1.charAt(i); for (int j = 0; j < str2.length(); j++) {...
74,758
What are the differences between a Java applet and a Java application?
The main difference between a Java applet and a Java application is that an applet is a client-side application that is downloaded from server and is run in a web browser, while a Java application is a stand-alone program which runs directly on the included JVM. Applet code is able to access resources from the server, ...
74,764
Write a Java program that prints all integers between 30 & 50 (inclusive).
public class PrintIntegers { public static void main(String[] args) { for(int i=30; i<=50; i++) { System.out.println(i); } } }
74,765
Write a Java method to calculate the total marks of a student given their marks of 5 subjects. int marks_sub1 = 80; int marks_sub2 = 90; int marks_sub3 = 85; int marks_sub4 = 92; int marks_sub5 = 87;
public static int calculateTotalMarks(int marks_sub1, int marks_sub2, int marks_sub3, int marks_sub4, int marks_sub5) { return marks_sub1 + marks_sub2 + marks_sub3 + marks_sub4 + marks_sub5; }
74,770
Given an array of strings and the task is to find the longest string from the given string array. ["Google", "Facebook", "Amazon", "Zapier" ]
public class LongestString { public static String getLongestString(String[] array) { if(array.length == 0) { return null; } String longestString = array[0]; for(int i = 1; i < array.length; i++) { if(array[i].length() > longestStrin...
74,837
Generate a code snippet to define a class called Animal in Java.
public class Animal { // instance variables private String name; private int age; // constructor public Animal(String name, int age) { this.name = name; this.age = age; } // methods public void eat() { System.out.println("I'm eating!"); } ...
74,849
Construct a for loop in Java to increment a counter from 0 to 10.
for (int i = 0; i < 10; i++) { System.out.println(i); }
74,878
Use Java to send an HTTP request to an API endpoint with a login form.
import java.net.*; import java.io.*; public class HttpClient { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/login"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Request headers con.setRequestMethod("POST"); ...
74,886
Create a Java program that takes a list of integers as an argument and computes the longest increasing subsequence. [8, 10, 1, 4, 15, 6, 7]
public class LongestIncreasingSubsequence { public static int longestSubsequence (int[] nums) { // Base case if (nums.length == 0) { return 0; } int[] dp = new int[nums.length]; dp[0] = 1; int maxLength = 1; for (int i=1; i < nums.length; i+...
74,887
Write a Java program that adds two numbers and checks whether the sum is greater than 5 or not. int x = 3; int y = 4;
public class Add { public static void main(String[] args) { int x = 3; int y = 4; int sum = x + y; if (sum > 5) { System.out.println("Greater than 5"); } else { System.out.println("Less than or equal to 5"); } } }
74,897
Rewrite the following code segment using Java 1.8's Lambda Expressions. BiFunction<Double, Double, Double> bf = new BiFunction<Double, Double, Double>() { public Double apply(Double d1, Double d2) { return (d1*d2)/2; } }
BiFunction <Double, Double, Double> bf = (d1, d2) -> (d1*d2)/2;
74,925
Write a for-loop in Java for printing the numbers from 1 to 10 with a space separating each number.
for (int i = 1; i <= 10; i++) { System.out.print(i + " "); }
74,952
Rewrite the following recursive algorithm in Java. def recursive(n): if n == 0: return 0 else: return n + recursive(n-1)
public static int recursive(int n) { if (n == 0) { return 0; } else { return n + recursive(n - 1); } }
74,958
Write a Java program to generate the following patterns using a for loop. * ** *** ****
public class Pattern { public static void main(String[] args) { for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++ ) System.out.print("*"); System.out.println(); } } }
74,970
Write a Java program to print out the lyrics of the song “Mary Had a Little Lamb”.
public class Lyrics { public static void main(String[] args) { System.out.println("Mary had a little lamb,"); System.out.println("Little lamb, little lamb,"); System.out.println("Mary had a little lamb,"); System.out.println("Its fleece was white as snow."); System.out.print...
74,984
Convert the following enum type expression in Java for days of the week to equivalent C# syntax. enum Weekday {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
enum Weekday { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
74,990
Convert the given code in Java to an equivalent expression in Python. int x = 10;
x = 10
74,992
Implement a Class in Java that creates a new array of two integers and allows the user to set and get the values of the array.
public class TwoIntegers { private int[] twoIntegers; public TwoIntegers() { twoIntegers = new int[2]; } public int getFirst() { return twoIntegers[0]; } public int getSecond() { return twoIntegers[1]; } public void setFirst(int first) { ...
74,997
Design a data structure in Java to store student records which includes Roll Number, Name, and Grade of the student.
public class Student { private int rollNumber; private String name; private int grade; public Student (int rollNumber, String name, int grade) { this.rollNumber = rollNumber; this.name = name; this.grade = grade; } public int getRollNumber() { return thi...
74,998
Edit the following Java code to round a number to two decimal places. double num = 3.14159;
double num = 3.14159; num = Math.round(num * 100.0) / 100.0; System.out.println(num); // Output: 3.14
75,010
Deducde whether the following code is a valid Java statement 345=num;
false
75,053
Generate a program in Java to find the mean of n numbers.
public class Mean { // Method to calculate the mean of n numbers static double mean(int numbers[]) { double sum = 0.0; for (int i : numbers) sum += i; return sum / numbers.length; } public static void main(String[] args) { int numbers[] = { 10, 20, 3...
75,064
Construct a Java method to convert a string to its equivalent title case format. String: this is the string to be converted
public static String toTitleCase(String input) { StringBuilder titleCase = new StringBuilder(); boolean nextTitleCase = true; for (char c : input.toCharArray()) { if (Character.isSpaceChar(c)) { nextTitleCase = true; } else if (nextTitleCase) { c = Character.toTitleCa...
75,065
Edit the Java code below to produce the output "My name is NAME". public class Test { public static void main(String[] args) { System.out.println("My name is"); } }
public class Test { public static void main(String[] args) { System.out.println("My name is NAME"); } }
75,142
Create a class in Java that represent books in a library.
public class Book { // Properties private String title; private String author; private int yearPublished; // Constructors public Book (String t, String a, int y) { title = t; author = a; yearPublished = y; } // Accessor and mutator method...
75,147
Change the following piece of Java code to make sure that the parameter passed is a valid date. public boolean isValidDate(String date){ // return true if date is valid }
public boolean isValidDate(String date){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { format.parse(date); return true; } catch (ParseException e) { return false; } }
75,150
Create a Java program to count character occurrences in a given string. String = "GPT models are a type of machine learning algorithms"
public class CharacterCount { public static void main(String[] args) { String str = "GPT models are a type of machine learning algorithms"; int[] count = new int[256]; for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; for (int i = 0; i < 256; i++) ...
75,162
Update the following Java code to print the difference between two dates in years, months and days import java.time.LocalDateTime; public class DateTime { public static void main(String[] args) { LocalDateTime dateTime1 = LocalDateTime.of(2020,11,5,14,45); LocalDateTime dateTime2 = LocalDateTime....
import java.time.LocalDateTime; import java.time.Period; public class DateTime { public static void main(String[] args) { LocalDateTime dateTime1 = LocalDateTime.of(2020,11,5,14,45); LocalDateTime dateTime2 = LocalDateTime.of(1999,1,15,9,30); Period diff = Period.between(dateTime1.toLoca...
75,172
Create a string object in Java that stores the text "Hello, World!".
String hello = "Hello, World!";
75,219
Create a Java program to compute the total price of a customer's order based on item prices and quantities. item_price = [30, 20, 15], quantity = [2, 4, 1]
public static int computeTotalPrice(int[] item_price, int[] quantity) { int sum = 0; for (int i = 0; i < item_price.length; i++) { sum += item_price[i] * quantity[i]; } return sum; } System.out.println(computeTotalPrice(item_price, quantity));
75,223
Create a boolean variable in Java, initialized to false.
boolean variable = false;
75,237
Create a class for a 2D vector in Java.
public class Vector2D { public double x, y; public Vector2D(double x, double y) { this.x = x; this.y = y; } public double magnitude() { return Math.sqrt(x * x + y * y); } public Vector2D add(Vector2D o) { return new Vector2D(x + o.x, y + o.y); } }
75,246
Use Java to create a constructor to set the values of instance variables num1 and num2.
public class Number { int num1; int num2; public Number(int num1, int num2) { this.num1 = num1; this.num2 = num2; } }
75,269
Create a Java class Person with instance variables firstName and lastName.
public class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
75,274
Construct an object-oriented program to print out the numerals from 1 to 10.
class Program { public static void main(String[] args) { for (int i=1; i<=10; i++) { System.out.println(i); } } }
75,286
How to access the element of a given array in Java? Array: [1, 5, 4, 8]
We can use the index of the element to access it. The syntax is arrayName[index]. For example, if we want to access the element at index 2, the syntax would be arrayName[2], and it would return the element with value 4.
75,289
Develop a Java program to input a string and reverse the order of words. I love to code in Java
Java in code to love I public class Reverse { static void reverseWords(String str) { // Specific marker to identify the strings String[] words = str.split("\\s"); String reversedString = ""; for (int i = 0; i < words.length; i++) ...
75,292
Create a class in Java to store the information about a user.
public class User { private String name; private int age; private String address; public User(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public String getName() { return name; } ...
75,295
Create a class in Java that comprises of a date, a location and temperature reading associated with that location on that particular date.
public class TemperatureReading { private Date date; private String location; private int temperature; public TemperatureReading(Date date, String location, int temperature) { this.date = date; this.location = location; this.temperature = temperature; } public Date getDate() { return date;...
75,359
Write a Java code snippet to show the below numbers in a tabular format on the console. num1 = 8 num2 = 10 num3 = 12
int [] nums = {8, 10, 12}; System.out.println("Number \tNumber \tNumber"); for(int i=0; i<nums.length; i++) { System.out.println(nums[i] + "\t\t" + nums[i+1] + "\t\t" + nums[i+2]); i++; }
75,365
Generate a code snippet in Java to display a message "Hello World!"
System.out.println("Hello World!");
75,370
Refactor the given piece of code in Java to make it more concise. int a = 5; int b = 10; int c = a + b;
int c = 5 + 10;
75,371
Change the following Java code so that it only prints the letters at even indices in the string. String str = "Hello, World!"; for (int i = 0; i < str.length(); i++) { System.out.print(str.charAt(i)); }
String str = "Hello, World!"; for (int i = 0; i < str.length(); i+=2) { System.out.print(str.charAt(i)); }
75,387
Create a short Java program that prints out a word 5 times. Word: hello
public class HelloWorld { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println("hello"); } } }
75,403
Write a Java program to convert a character to an int. 'A'
public class Main { public static void main(String[] args) { char ch = 'A'; int asciiCode = (int) ch; System.out.println("ASCII code of 'A' :" + asciiCode); } }
75,431
Write a Java class named "Shape" which has an abstract method named "surfaceArea".
public abstract class Shape { public abstract double surfaceArea(); }
75,446
Develop a code snippet in Java to create a thread that runs a simple print statement every 5 seconds.
public class MyTask implements Runnable { public void run() { while (true) { System.out.println("This is the task running every 5 seconds."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStack...
75,463
Refactor the following Java code to improve readability and dynamism. public class Movies { private int movieCount = 5; private String genre = "action"; public void printMovieDetails() { System.out.println("The movie count is " + movieCount); System.out.println("The genre is " + genre); } }
public class Movies { private int movieCount; private String genre; public Movies(int movieCount, String genre) { this.movieCount = movieCount; this.genre = genre; } public void printMovieDetails() { System.out.println("The movie count is " + movieCount); System.out.println("The genre is "...
75,473
Write code in Java to find the maximum value of the array. [1, 4, 6, 8, 9, 4, 2]
public static double maxValue(double[] array) { double maxValue = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > maxValue) maxValue = array[i]; } return maxValue; }
75,528
Write a short piece of code in Java to display the following message.
System.out.println("Welcome to the Java programming course!");
75,530
Write a piece of code in Java to check if the following string contains a numeric character. "Hello World!"
String str = "Hello World!"; boolean isNumeric = false; for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { isNumeric = true; break; } } if (isNumeric) System.out.println("The given string contains a numeric character."); else System.out.pr...
75,536
In Java, develop a program which prints the size of a given array. int[] array = {1,2,3,4,5};
public class main{ public static void main(String[] args){ int[] array = {1, 2, 3, 4, 5}; System.out.println("Size of the array is: " + array.length); } }
75,538
Convert the following SQL query into a Java code using JDBC. SELECT Employees.Name FROM Employees WHERE Employees.Salary > 50000
String queryString = "SELECT Employees.Name FROM Employees WHERE Employees.Salary > ?"; PreparedStatement pstmt = conn.prepareStatement(queryString); pstmt.setDouble(1, 50000); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String name = rs.getString(1); // Process the name }
75,548
Write a Java program to find the sum of two arrays of length 10
public static int[] sumArrays(int[] arr1, int[] arr2){ int[] result = new int[arr1.length]; for(int i=0; i<arr1.length; i++){ result[i] = arr1[i] + arr2[i]; } return result; }
75,573
Construct a for loop in Java which will iterate through an array and print each item in a new line. int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
75,579
Create a Java program that reads in a sentence from the user and prints out the lengths of each word in the sentence. This is a sentence
4 2 1 8
75,601
Create a Java program that reads in two strings and outputs their longest common substring. myCodingSkillzz and AnotherCodingSkill
CodingSkill
75,602