instruction
stringlengths
25
5.05k
output
stringlengths
4
8.53k
__index_level_0__
int64
34
78.2k
Create a class in Java called Student with 3 instance variables - firstName, lastName, and age.
public class Student{ String firstName; String lastName; int age; //constructor Student(String firstName, String lastName, int age){ this.firstName = firstName; this.lastName = lastName; this.age = age; } }
70,091
Create a Java program to multiply two given matrices
public class MatrixMultiplication { // Method to multiply two matrices public static double[][] multiply(double[][] A, double[][] B) { int aRows = A.length; int aColumns = A[0].length; int bRows = B.length; int bColumns = B[0].len...
70,115
Given two arrays in Java, how would you merge them into one array? int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6};
int[] mergedArray = new int[array1.length + array2.length]; System.arraycopy(array1, 0, mergedArray, 0, array1.length); System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
70,128
Create a binary heap sort algorithm in Java.
public class Heapsort { public 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--) { ...
70,146
Write a Java program to display the area of a given circle. radius = 7
public class Circle { public static void main(String[] args) { double radius = 7.0; double circArea = Math.PI * (radius * radius); System.out.println("The area of the circle with radius" + radius + " is: " + circArea); } }
70,236
Create a variable and assign a value to it in Java.
String name = "John";
70,276
Create a Java class that defines a circle with two double data fields, radius and area.
public class Circle { private double radius; private double area; public Circle(double radius) { this.radius = radius; this.area = Math.PI * Math.pow(this.radius, 2); } public double getRadius() { return this.radius; } public double getArea() { return this.area; } }
70,298
Write a Java program for binary search.
public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left)/2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; ...
70,398
Create a Hashtable in Java to store a list of key-value pair.
import java.util.Hashtable; public class HashtableExample { public static void main(String args[]) { Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); ht.put(1, "Code"); ht.put(2, "Learn"); ht.put(3, "Project"); ht.put(4, "University"); Sys...
70,410
Override the equals method for a Java class named Point. class Point { int x; int y; }
public class Point { int x; int y; @Override public boolean equals(Object obj) { if (obj instanceof Point) { Point other = (Point) obj; return x == other.x && y == other.y; } return false; } }
70,427
Create a class in Java for a rectangle shape with length and breadth as attributes.
public class Rectangle { int length; int breadth; Rectangle(int l, int b) { length = l; breadth = b; } int calculateArea() { return length * breadth; } }
70,453
Convert the following string to an array of characters in Java. String str = "Hello World!"
char[] array = str.toCharArray();
70,464
Modify the following program to print the number of occurrences of the character e in string s. String s = "Hello World!"
String s = "Hello World!"; int count = 0; for (int i=0; i < s.length(); i++) { if (s.charAt(i) == 'e') { count++; } } System.out.println("The number of occurrences of character 'e' in the string is: " + count);
70,465
Create a script in Java that builds a string based on a given character repeated n number of times. Character = '*' Number = 5
""" Create a script in Java that builds a string based on a given character repeated n number of times. """ public class StringBuilder { public static String buildString(char c, int n){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ sb.append(c); } ...
70,509
Write a code to find the first 4 terms of the Fibonacci sequence in Java.
public class Fibonacci { public static int[] getFibonacciNumbers(int numTerms) { int[] sequence = new int[numTerms]; int firstTerm = 0, secondTerm = 1; sequence[0] = firstTerm; sequence[1] = secondTerm; for (int i = 2; i < numTerms; i++) { sequence[i] = fi...
70,538
How would you format the following date in mm/dd/yyyy format using Java? 5 January 2020
import java.text.SimpleDateFormat; import java.util.Date; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); String date_string = sdf.format(new Date(2020, 0, 5)); System.out.println(date_string); # Output: "01/05/2020"
70,574
Write a Java program to find out the longest word from a sentence. String sentence = "This is a sample sentence"
public class LongestWord { // Function to find longest word in the sentence static String findLongestWord(String str) { String longestWord = ""; String[] words = str.split(" "); for (int i = 0; i < words.length; i++) { if (words[i].length() > longestWord.length())...
70,598
Compare two strings using Java
public static int compare(String s1, String s2) { return s1.compareTo(s2); }
70,623
Convert the following code written in Java to C++. String s = "It's raining today";
std::string s = "It's raining today";
70,627
Create a Java program to compare two strings and check if they are equal or not. String s1 = "Hello"; String s2 = "World";
public static boolean compareStrings(String s1, String s2) { return s1.equals(s2); }
70,658
Write a Java program to print the Fibonacci sequence starting from given number. Starting Number: 10
public class Fibonacci { public static void main(String[] args) { int n1 = 10, n2 = 0, n3, i; System.out.print(n1 + " "); for (i = 1; i <= 8; ++i) { n3 = n1 + n2; System.out.print(n3 + " "); n1 = n2; n2 = n3; } } }
70,679
Given a 2D array of integers, write a Java method to find the sum of an hourglass pattern. The 2D array of integers are: [[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]]
public static int findSumOfHourglass(int[][] arr){ int sum = 0; for(int i = 0; i < arr.length - 2; i++){ for(int j = 0; j < arr[i].length - 2; j++){ int tempSum = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+...
70,680
How do you connect to PostgreSQL database using Java?
You can connect to PostgreSQL database using Java by using the JDBC driver. First, import the PostgreSQL JDBC driver class. Then, create an instance of the driver using a connection string and username and password. Finally, use the DriverManager class's getConnection() method to obtain a java.sql.Connection object tha...
70,682
How do you use the Set structure in Java?
The Set interface in Java provides an unsorted, unordered collection of objects that cannot contain duplicates. The Set interface is part of the Java Collection Framework and provides methods such as add(), remove() and contains() which allow you to manipulate the set. The Set interface is implemented by the HashSet cl...
70,683
Given two linked lists, write a Java program to merge them. The two linked lists are: List1 (1 -> 4 -> 5 -> 8 -> 10) List2 (2 -> 3 -> 6 -> 7 -> 9)
public static ListNode mergeLinkedLists(ListNode head1, ListNode head2) { if(head1 == null) return head2; if(head2 == null) return head1; ListNode mergedList; if(head1.val < head2.val) { mergedList = head1; mergedList.next = mergeLinkedLists(head1.ne...
70,687
Generate a code in Java to compute the average of 5 numbers. Compute the average of 8, 5, 10, 3 and 9
public class Average { public static void main(String args[]) { double nums[] = {8, 5, 10, 3, 9}; double result = 0; int i; for (i=0; i<5; ++i) { result = result + nums[i]; } System.out.println("Average is " + result / 5); } }
70,689
Rewrite the code below using Java def print_list(list): for item in list: print(item)
void printList(List<String> list) { for (String item : list) { System.out.println(item); } }
70,698
Construct an array of 10 elements in Java and initialize each element to 0.
int[] array = new int[10]; for (int i = 0; i < array.length; i++) { array[i] = 0; }
70,711
Construct a class in Java that has two methods called 'sayHello' and 'sayGoodbye'.
class HelloGoodbye { public static void sayHello() { System.out.println("Hello!"); } public static void sayGoodbye() { System.out.println("Goodbye!"); } }
70,714
Create a Java program to implement a doubly linked list with the following operations: insert, delete, display.
class Node { int data; Node previous; Node next; public Node(int data) { this.data = data; this.previous = null; this.next = null; } } class DoublyLinkedList { Node head; // Inserts a new Node at front of the list public void push(int new_data)...
70,724
Create a class in Java that encapsulates a student's name and grade point average (GPA).
public class Student { private String name; private double gpa; public Student(String name, double gpa) { this.name = name; this.gpa = gpa; } public String getName() { return name; } public double getGPA() { return gpa; } }
70,736
Print the output of adding two integers in Java. int a = 10; int b = 20;
int a = 10; int b = 20; int c = a + b; System.out.println(c); // Outputs 30
70,741
Correct the following code in Java. public class HelloWorld { public static Void main(String[] args) { System.out.println("Hello World!"): } }
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
70,743
Using Java, write a program to find the sum of natural numbers from 1 to an input number. 10
public class Sum { public static void main(String[] args) { int num = 10; int sum = 0; for (int i = 1; i <= num; i++) { sum += i; } System.out.println("Sum of natural numbers from 1 to " + num + " is " + sum); } }
70,752
Write a Java code to read a string from the user and print it reversed.
import java.util.Scanner; public class ReverseString { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String str = in.nextLine(); in.close(); char[] arr = str.toCharArray(); for (int i = arr...
70,772
Explain how garbage collection works in Java.
Garbage collection in Java works by periodically running a garbage collector to identify and reclaim memory occupied by objects that are no longer referenced. This process is done in order to free the memory for use by other objects and to prevent memory leaks. The Java Virtual Machine implements the garbage collection...
70,789
Create a for loop in Java to print out the integers from 10 to 1 in decreasing order.
for(int i=10; i>=1; i--) { System.out.println(i); }
70,812
Compute the following expression in Java. 5 + 10 * 3
int result = 5 + (10 * 3); System.out.println(result); // Output: 35
70,814
Write a class in Java that contains two method to add and subtract two numbers.
public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } }
70,815
Design a class in Java to represent a student, with their name and grade fields.
public class Student { String name; String grade; public Student(String name, String grade) { this.name = name; this.grade = grade; } public String getName() { return this.name; } public String getGrade() { return this.grade; } }
70,859
Compare and contrast the features of the two programming languages: Python and Java.
Python and Java are both popular programming languages with different features that make them suitable for different tasks. Python is an interpreted, high-level, and general-purpose programming language that emphasizes code readability and has simple, easy-to-use syntax. Java, on the other hand, is an object-oriented, ...
70,893
Implement a method in Java to reverse a number
public class ReverseNumber { public static int reverseNumber(int num) { int reversed = 0; while(num > 0) { reversed *= 10; reversed += num % 10; num /= 10; } return reversed; } }
70,916
Construct a for loop in Javascript to measure the sum of the squares of integers from 2 to 6
let sum = 0; for (let i = 2; i <= 6; i++) { sum += i * i; } console.log(sum);
70,919
What is multithreading in Java and why is it used?
Multithreading in Java is a process which allows multiple threads to run concurrently, allowing applications to utilize multiple CPU cores and execute operations simultaneously. It helps to improve the performance of applications by allowing them to complete operations quickly and efficiently.
70,924
How would you delete an item from a linked list in Java?
To delete an item from a linked list in Java, you would first need to traverse the list until you reach the item. Once you find the item, delete the reference to the node immediately before it by pointing the previous node's 'next' pointer to the node after the current one. Finally, delete the node by setting the node'...
70,926
Write code in Java for a user input prompt that states "Please enter a number".
Scanner input = new Scanner(System.in); System.out.println("Please enter a number: "); int number = input.nextInt();
70,936
Write a code in Java to sort given list items in ascending order. my_list = [9, 4, 7, 2, 6]
for (int i = 0; i < my_list.length; i++) { for (int j = i + 1; j < my_list.length; j++) { if (my_list[i] > my_list[j]) { int temp = my_list[i]; my_list[i] = my_list[j]; my_list[j] = temp; } } }
70,955
Design a class in Java for creating a 2D point.
public class Point { double x,y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public double distance(Point other)...
70,961
Develop a program to join two strings String1 = "Hello"; String2 = "World";
public class ConcatenateStrings { public static String concat(String s1, String s2) { StringBuilder sb = new StringBuilder(); sb.append(s1); sb.append(s2); return sb.toString(); } public static void main(String[] args) { String str1 = "Hello"; String str2 = "World"; Syst...
70,983
Create a Java program to delete an element for a given position in an array. [1, 3, 5, 6, 8], position=2
public static int[] deleteElement(int[] arr, int pos) { int n = arr.length; int i; // Removing the element at a given position for (i = pos; i < n - 1; i++) arr[i] = arr[i+1]; // Returning the resulting array return arr; } public static void main(String[] args) { int[] arr = {1, 3, 5, 6, 8}; int pos = 2;...
70,998
Determine the most efficient way to sort a complex data structure using Java. [3, 4, 2, 7, 9, 1, 5]
public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public void quickSort(int[] arr, int start, int end) { if (start < end) { int partitionIndex = partition(arr, start, end); quickSort(arr, start, partitionIndex-1); quickSort(arr, partitionIndex+1, ...
71,027
In Java, what is a good way to make a deep copy of an object?
A deep copy of an object can be obtained by using the Object.clone() method or by serializing and deserializing the object.
71,080
Write a Java code to create a HashMap and add elements into it. //Given Key and Value // key: "name" // value: "John"
HashMap<String, String> map = new HashMap<>(); map.put("name", "John");
71,106
Produce the Java equivalent of the following PHP code block. $arr = array(1, 2, 3, 4); foreach ($arr as $element) { echo $element; }
int[] arr = {1, 2, 3, 4}; for (int element : arr) { System.out.println(element); }
71,132
Explain the role of the "break" keyword in a switch statement in Java.
The "break" keyword is used in a switch statement to terminate the switch block. When it is encountered, the code execution jumps to the line immediately after the switch block. It is also used to exit out of a loop if a certain specified condition is met.
71,134
Create a class in Java which stores the details of a book (title, author, ISBN).
class Book { String title; String author; String isbn; public Book(String title, String author, String isbn) { this.title = title; this.author = author; this.isbn = isbn; } }
71,137
Write a Java program which prints out the maximum element in an array. nums = [6, 4, 7, 2, 8]
public static int maxElement(int[] nums) { int max = 0; for (int i = 0; i < nums.length; i++) max = Math.max(nums[i], max); return max; }
71,138
Design an algorithm in Java to reverse a list of integers. list = [1,2,3,4,5]
public static void reverseList(List<Integer> list) { Collections.reverse(list); }
71,222
Create a customer class in Java that can be used to store information about customers. Create a class with field names: id (integer), firstName (text), lastName (text), email (text), address (text)
public class Customer { private int id; private String firstName; private String lastName; private String email; private String address; // getter and setter methods public int getId() { return id; } public void setId(int id) { this.id = id; } ...
71,244
Write a Java method to check if a string is a palindrome (same forwards and backwards). string = "racecar"
""" Java method to check if a string is a palindrome """ public static boolean isPalindrome(String s) { //base case if(s.length() == 0 || s.length() == 1) return true; if(s.charAt(0) == s.charAt(s.length()-1)) return isPalindrome(s.substring(1, s.length()-1)); //if not match ret...
71,249
Design a class in Java that stores the number of letters, numbers, and special characters in a given string.
""" Java class to store the number of letters, numbers and special characters in a given string """ public class StringInfo { // Instance Variables int letterCount; int numberCount; int specialCharCount; // Constructor to initialize all the instance variables public StringInfo() { thi...
71,250
Modify the following Java program to print "Hello world!" without using a System.out.print statement. class HelloWorld { public static void main(String args[]) { System.out.print("Hello world!"); } }
class HelloWorld { public static void main(String args[]) { System.out.println("Hello world!"); } }
71,262
Implement a Java code to print the first 10 multiples of a given number
public class Multiples { public static void main(String[] args) { int number = 5; for (int i = 1; i <= 10; i++) { System.out.println(number*i); } } }
71,293
Find the fifth smallest number in a list of numbers using Java. list of numbers: [23, 12, 15, 7, 34, 19]
int compareToFindSmallest(int[] numbers, int targetIndex) { int smallestIndex = 0; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < numbers[smallestIndex]) { smallestIndex = i; } } int tempIndex = smallestIndex; int resultIndex = -1; int count = 0; ...
71,298
Write a class definition in Java to create a Person object with the properties age, name, and hobby.
public class Person { private int age; private String name; private String hobby; //constructors public Person(int age, String name, String hobby) { this.age = age; this.name = name; this.hobby = hobby; } //getters public int getAge() { return age; } public String getNam...
71,397
Write a Java class to implement a priority queue data structure.
public class PriorityQueue { private int size; private int[] data; public PriorityQueue(int capacity) { this.size = 0; this.data = new int[capacity]; } public void add(int item) { if (this.size == this.data.length) { throw new IllegalStateException("The queue is full!"); } this.da...
71,402
Compile a Java program using the command line.
javac filename.java
71,427
Write a Java program to generate a schedule for students with a given set of available IDs. IDs to be scheduled [1, 2, 3]
import java.util.ArrayList; import java.util.List; public class ScheduleGenerator { public static void main(String[] args) { List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); System.out.println(generateSchedule(ids)); } public static List<Integer> generateS...
71,517
Create a Java class to represent a new type of vehicle called hovercar.
public class Hovercar { // Properties private String color; private int maxSpeed; private int currentSpeed; // Constructor public Hovercar(String color, int maxSpeed) { this.color = color; this.maxSpeed = maxSpeed; this.currentSpeed = 0; } // Getters and Setters public String getColo...
71,520
Define a Java annotation for a class.
@interface MyAnnotation { String author() default "unknown"; int date(); }
71,522
Create a Java program to take an integer input from the user and print its factorial.
import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int n = sc.nextInt(); int factorial = 1; for (int i = 1; i <= n; i++) { factorial = factorial * i; } System.out.println("The factori...
71,526
How is an immutable object different from a mutable object in Java?
In Java, an immutable object is an object whose state cannot be modified once it is created. An immutable object's state can still be accessed, but its properties cannot be changed. Mutable objects, on the other hand, can be modified after they are created. This is accomplished by providing methods to modify its proper...
71,531
What code should be used to generate 5 random numbers in Java?
Random random = new Random(); int[] numbers = new int[5]; for(int i = 0; i < 5; i++) { numbers[i] = random.nextInt(); }
71,564
Create a Java program to print out factorials from 1 to 10.
public class Factorial { public static void main(String[] args) { for (int i = 1; i <= 10; ++i) { System.out.println(i + "! = " + factorial(i)); } } public static long factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1...
71,661
Convert the given Python code to Java def foo(a, b): return a*b
public int foo(int a, int b) { return a * b; }
71,673
Calculate the value of 3^4 using Java code.
int result = (int)Math.pow(3, 4);
71,689
Generate the syntax to declare a variable called 'result' as an integer in Javascript.
let result = 0;
71,711
Write an algorithm in Java to check if a number is a prime number. A prime number is an integer greater than 1 that is only divisible by 1 and itself.
public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= ...
71,732
Write a Java code that adds two numbers, a and b, and returns their sum. int a = 2 int b = 3
public int sum(int a, int b) { return (a + b); }
71,740
Write a simple Java class
public class MyClass { public static void main(String[] args) { System.out.println("Hello World!"); } }
71,757
Create a Java program to sort an array of integers by implementing the Selection Sort technique.
public static void selectionSort(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 = arr[min_idx]; arr[min_idx] = arr[i]; ...
71,783
Write a Java program to display a pyramid with the given height. height = 3
public class Pyramid { public static void printPyramid(int height) { int i, j; for (i=0; i<height; i++) { for (j=0; j<=i; j++) { System.out.print("* "); } System.out.println(); } } public stati...
71,818
Write Java code to create a class called Card with two string fields, rank and suit.
public class Card { private String rank; private String suit; // constructor public Card(String rank, String suit) { this.rank = rank; this.suit = suit; } // getters public String getRank() { return rank; } public String getSuit() { return suit...
71,845
Write a Javascript program to convert a given string into all uppercase characters. String: "Welcome to the World !"
let str = "Welcome to the World !"; let upperCaseStr = str.toUpperCase(); console.log(upperCaseStr); # Output: "WELCOME TO THE WORLD !"
71,847
Use the Java language to print out ‘Hello World’.
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
71,856
Design a class in Java to represent a bank account that has a balance, a name, and an account number.
public class BankAccount { private String name; private String accountNumber; private double balance; public BankAccount(String name, String accountNumber, double balance) { this.name = name; this.accountNumber = accountNumber; this.balance = balance; } public void depo...
71,878
Implement a search algorithm in Java.
public class SearchAlgorithm { public int search(int[] array, int target) { int left = 0; int right = array.length - 1; while (left <= right) { int mid = (left + right) / 2; if (target == array[mid]) { return mid; } if (target < array[mid]) { right = mid...
71,901
Create an object of type Car in Java.
public class Car { private String make; private String model; private String color; //getters and setters public Car(String make, String model, String color) { this.make = make; this.model = model; this.color = color; } public String getMake() { return make...
71,903
Design a die roll program in Java.
import java.util.Random; public class RollDie { public static void main(String[] args) { // creating instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 6 int rand_int = rand.nextInt(6); // Print random integers...
71,924
Add exception handling for user-defined errors to the following code snippet in Java. public class MyClass { public static void main(String[] args) { int x = 4; int y = 2; int z = x/y; System.out.println(z); } }
public class MyClass { public static void main(String[] args) { try { int x = 4; int y = 2; int z = x/y; System.out.println(z); } catch (ArithmeticException ex) { System.out.println("Division by zero not allowed."); } } }
71,993
Create a for-loop structure in Java that prints out each index in the array A from 0 to the length of A minus 1. int[] A = {1, 2, 3, 4, 5}
for(int i = 0; i < A.length; i++) { System.out.println("A[" + i + "] = " + A[i]); }
72,006
Reverse the following linked list in Java. // single linked list Node { int data; Node next; } head | V 1 -> 2 -> 3 -> 4 -> NULL
// single linked list Node { int data; Node next; } head | V 4 -> 3 -> 2 -> 1 -> NULL
72,009
Write an if-else statement in Java to check if a given number is greater than or equal to 15. Number: 9
int number = 9; if (number >= 15) { System.out.println("Number is greater than or equal to 15"); } else { System.out.println("Number is less than 15"); }
72,025
Create a thread-safe Java method that increments a given counter.
public static synchronized void incrementCounter(int counter) { counter += 1; }
72,031
Implement a linked list structure with an insert method using Java.
class Node { int data; Node next; Node (int data) { this.data = data; this.next = null; } } class LinkedList { Node head; public void insert(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (curren...
72,047
Write a Java program to take in 3 strings and combine them into one. string1 = "hello" string2 = "world" string3 = "!"
public class CombineStrings { public static void main(String[] args) { String string1 = "hello"; String string2 = "world"; String string3 = "!"; String output = string1 + string2 + string3 ; System.out.println(output); //hello world! } }
72,099
Create a Java program to determine whether a given string is a palindrome. A palindrome is a string which reads the same forwards and backwards.
public class Palindrome { public static boolean isPalindrome(String s) { int i = 0, j = s.length()-1; while (i < j) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } public static void ...
72,101
Construct a for loop in Java for iterating through an array.
for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
72,115
Write some Java code to fill in an array of size n with all consecutive numbers from 1 to n.
public void fill(int[] array, int n) { for (int i = 0; i < n; i++) { array[i] = i + 1; } }
72,127
Rewrite the following Java code into SQL to select all the distinct elements from a table. String sql = "SELECT DISTINCT * FROM table_name";
SELECT DISTINCT * FROM table_name;
72,129