instruction
stringlengths
25
5.05k
output
stringlengths
4
8.53k
__index_level_0__
int64
34
78.2k
Write a Java program to find the index of the first occurrence of the given element in an array. int[] array = {1, 7, 3, 6, 4, 7}; int num = 7;
public class FindFirstIndex { public static void main(String[] args) { int[] array = {1, 7, 3, 6, 4, 7}; int num = 7; int idx = -1; for(int i = 0; i < array.length; i++) { if(array[i] == num) { idx = i; break; } } ...
66,716
Create an array in Java containing two objects.
Object[] myArray = {object1, object2 };
66,734
Write a Java program to append two given lists. list1 = [10, 20, 30] list2 = [5, 15, 25]
import java.util.ArrayList; public class AppendLists { public static ArrayList<Integer> appendLists(ArrayList<Integer> list1, ArrayList<Integer> list2) { ArrayList<Integer> appendedList = new ArrayList<>(list1); appendedList.addAll(list2); return appendedList; } public static void main(String[] args...
66,760
Write a Java code snippet to declare a two dimensional array of size 2×3.
int[][] arr = new int[2][3];
66,776
In Java, write a method which takes a two-dimensional array as input and prints it in spiral order. [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
public void printSpiral(int[][] matrix) { int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1; int dir = 0; while (top <= bottom && left <= right) { // Move left to right if (dir == 0) { for (int i = left; i <= right; i++...
66,784
Design a Java method to retrieve the maximum value from an array. [2, 3, 5, 9, 6, 11]
public static int getMax(int[] arr) { int max = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; }
66,883
Develop an algorithm in Java that removes duplicate elements from an array. [1, 3, 5, 3, 4, 5]
public static int[] removeDuplicates(int[] arr) { int n = arr.length; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i = 0; i < n-1; i++) if (arr[i] != arr[i+1] ) ar...
66,886
Construct a simple Java program that calculates the sum of two integers.
public class Sum { public static void main(String[] args) { int a = 5; int b = 10; int sum = a + b; System.out.println("The sum of the two integers is: " + sum); } }
66,892
Write a Java program to remove the duplicates in an array.
import java.util.HashSet; public class RemoveDuplicates { public static int[] removeDuplicates(int[] nums) { HashSet<Integer> set = new HashSet<>(); for (int num : nums) set.add(num); int[] result = new int[set.size()]; int i = 0; for (int num : set) result[i++] = num; return result; } }
66,894
Create a Javascript class called "Car" that takes an argument called "year" and prints the value of "year".
class Car{ constructor(year){ this.year = year; } printYear(){ console.log(this.year); } }
66,904
Define a constructor in Java to create an instance of a class.
public class MyClass { // Constructors public MyClass() { // Default constructor } // Constructor with parameters public MyClass(int a, int b) { // Do something with the parameters } }
66,911
Name the Java keyword used to define a class
The Java keyword used to define a class is "class".
66,924
Design a program to convert an array of characters to its equivalent string. array = [ 'A', 'B', 'C', 'D' ]
public class ArrayToString { public static String convert(char[] arr) { StringBuilder sb = new StringBuilder(); for (char c : arr) sb.append(c); return sb.toString(); } public static void main(String[] args) { char[] arr = { 'A', 'B', 'C', 'D'...
66,926
Create a program that determines whether a given numbers is a prime.
public class PrimeNumber { public static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } public static void main(String[] args) { for (int i = 0; i < 20; i++) { if (isPrime(i)) { System.o...
66,927
Create a Java method that takes in an integer array and returns it sorted. [7, -2, 4, 21, 0]
public static int[] sortInteger(int[] arr) { int[] sortedArr = Arrays.copyOf(arr, arr.length); Arrays.sort(sortedArr); return sortedArr; }
66,935
Initialize a new enum type in Java that stores the information of colors.
public enum Color { RED, GREEN, BLUE }
66,937
Create a program in Java that outputs a Fibonacci series of length n.
public class Fibonacci { // Function to print the nth // fibonacci number static void printFibonacciSeries(int n) { int a = 0, b = 1, c; if (n == 0) { System.out.print(a); return; } for (int i = 2; i <= n; i++) { c = a + b; ...
66,959
Write a Java method that accepts two integers and returns their least common multiple.
public static int lcm(int a, int b) { int gcd = 1; for(int i = 1; i <= a && i <= b; ++i) { // Checks if i is factor of both integers if(a % i == 0 && b % i == 0) gcd = i; } int lcm = (a*b) / gcd; return lcm; }
66,966
Write a Java program to find the area of a triangle where the three sides are given as x, y, and z. x = 6, y = 7, z = 8
public class AreaOfTriangle { public static void main(String[] args) { int x = 6, y = 7, z = 8; double s = (x + y + z) / 2; double area = Math.sqrt(s * (s - x) * (s - y) * (s - z)); System.out.println("Area of triangle: " + area); } }
67,005
Given an array of objects, sort them in descending order according to their age. array = [ {name: 'John', age: 25}, {name: 'Peter', age: 32}, {name: 'Alex', age: 21} ]
import java.util.Arrays; import java.util.Comparator; public class SortByAge { public static void main(String[] args) { // Array of objects object[] array = { {name: 'John', age: 25}, {name: 'Peter', age: 32}, {name: 'Alex', age: 21} }; // Sorting array of objects by ag...
67,007
Write a Java program to clone an array of objects.
public class CloneObjectArray { public static void main(String[] args) { // Creating an array of objects Employee[] employees = {new Employee("John", 25), new Employee("Tim", 30), new Employee("Tom", 35)}; // Cloning the array Employee[] clone = employ...
67,008
Describe the basics of programming for a beginner.
Programming is the process of writing computer code to create programs that can perform specific tasks or operations. It involves using a programming language to give instructions to a computer to carry out a specific task. A program can involve calculations, data processing, and more complex tasks such as simulation, ...
67,048
Create an array of 10 numbers in Java and assign random values from 1 to 10 to each item of the array.
int[] nums = new int[10]; Random rand = new Random(); for(int i=0; i<nums.length; i++) { nums[i] = rand.nextInt(10) + 1; }
67,055
Construct a query in Java to find the last day of the month.
Calendar now = Calendar.getInstance(); int lastDayOfMonth = now.getActualMaximum(Calendar.DAY_OF_MONTH);
67,073
Develop a for loop in Javascript to output integers from 0 to 10
for (let i = 0; i < 11; i++) { console.log(i); }
67,089
Write a Java program to replace all non-alphanumeric characters with underscores. Hello, World!
public class ReplaceNonAlpha { public static void main(String[] args) { String string = "Hello, World!"; string = string.replaceAll("[^A-Za-z0-9]", "_"); System.out.println(string); } }
67,090
Generate a unique ID string in Java.
import java.util.UUID; public class App { public static void main(String[] args) { // generate a unique ID string String uniqueID = UUID.randomUUID().toString(); System.out.println("Unique ID String: " + uniqueID); } }
67,169
Write an expression in Java to calculate the exponential value of a number.
Math.exp(x)
67,173
Debug the following Java code snippet to makes sure it is syntactically correct: public class Test { public static void main(String[] args) { int num1 = 0; int num2 = 0; if (num1 = 0) { num2 = 1; } } }
public class Test { public static void main(String[] args) { int num1 = 0; int num2 = 0; if (num1 == 0) { num2 = 1; } } }
67,174
Edit the following Java code to create a method which will calculate the area of a rectangle, given its width and length. public class Rectangle { private double width; private double length;
public class Rectangle { private double width; private double length; public double calculateArea() { return width * length; } }
67,226
Write a Java program that counts the number of vowels in a given string. String str = "This is a test string";
public class VowelCounter { public static int countVowels(String str) { int count = 0; for(int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); if(currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' || currentChar == 'u') { count++; } } return cou...
67,229
Create a Java program to implement the classic Tic Tac Toe game.
import java.util.Scanner; public class TicTacToe { public static char[][] board = new char[3][3]; public static boolean playerX; public static Scanner scan; public static void main(String[] args) { scan = new Scanner(System.in); playerX = true; initializeBoard(); w...
67,267
Write a code in Java to find the GCD of two numbers
public static int gcd(int num1, int num2) { if(num2==0) return num1; return gcd(num2, num1%num2); }
67,305
Write a Java program to find the second most frequent character in a string. String: "Hello World!"
public class SecondMostFrequent { public static char findSecondMostFrequent(String str) { int[] counts = new int[26]; for(int i = 0; i < str.length(); i++) counts[str.charAt(i)- 'a']++; int index = 0; int max_count = 0; for(int i = 0; i < str.length(); i++) { if(counts[str.ch...
67,336
Describe what is polymorphism in Java.
In Java, polymorphism is a programming concept that allows the same code to be used to perform different tasks. This is achieved by assigning different behaviors to different objects that share a common base class. Thus, when a method is invoked, the runtime determines which version of the method should be executed by ...
67,338
Create a class in Java to build a singly linked list.
public class SinglyLinkedList { Node head; // head of list // Linked list Node. // This inner class is made static // so that main() can access it static class Node { int data; Node next; Node(int d) { data = d; next = nu...
67,382
Construct a while loop with an if-else statement in Java to print all odd numbers between 1 to 10.
int i = 1; while (i <= 10) { if (i % 2 != 0) { System.out.print(i + " "); } i++; }
67,414
Create a program that calculates the area of a triangle using C#. base = 10 height = 8
public class AreaCalculator { public static void main(String[] args) { int base = 10; int height = 8; double area = (base*height)/2; System.out.println("The area of the triangle is: "+area); } }
67,423
Create a Java program to compute the distance between two points. PointA = (2, 3) PointB = (4, 9)
public class DistanceCalculator { public static double distanceCalculator(int x1, int y1, int x2, int y2) { double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); return distance; } } class DistanceCalculatorTest { public static void main(String[] args) { double...
67,442
Suppose you have two dictionaries, A and B. Write a code in Java to find the intersection of A and B. A = {1: 'a', 2: 'b'} B = {2: 'b', 3: 'c'}
public static HashMap<Integer, String> intersect(HashMap<Integer, String> A, HashMap<Integer, String> B) { HashMap<Integer, String> result = new HashMap<>(); for (Integer key: A.keySet()) { if (B.containsKey(key)) { result.put(key, A.get(key)); } } return result; }
67,457
Write a Java program to find the length of a string without using the length() method.
public static int stringLength(String str){ int count = 0; for (int i=0; i<str.length(); i++){ if(str.charAt(i)!=' '){ count++; } } return count; }
67,466
Write a Class in Java that represents a student.
public class Student { private String firstName; private String lastName; private int studentId; public Student(String firstName, String lastName, int studentId) { this.firstName = firstName; this.lastName = lastName; this.studentId = studentId; } public String getFirstName() { return firs...
67,484
What is the output of the following Java code? int x = 7; int y = 3; int z = x % y;
The output is that the value of z is 1.
67,490
Implement quick sort in Java.
public static void quickSort(int[] arr, int low, int high) { if (arr == null || arr.length == 0) return; if (low >= high) return; // pick the pivot int middle = low + (high - low) / 2; int pivot = arr[middle]; // make left < pivot and right > pivot int i = low, j = high...
67,494
In Java, write a program that finds the sum of two linked lists representing integers.
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x ...
67,499
Modify the code to make sure it is valid according to Java language specification. 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!"); } }
67,509
Parse a user input in the following format and print it out. x - 10, y - 20
int x = 10; int y = 20; System.out.println("x = " + x + " y = " + y);
67,510
Override the "toString" method for a given class in Java.
public class MyClass { public String toString() { return "MyClass Object"; } }
67,546
Update the Java code to check the condition that the value of "amount" is greater than 1000 or not. public class Main { public static void main(String args[]){ double amount = 1100; // TODO System.out.println("The amount is greater than 1000: "+ amount); } }
public class Main { public static void main(String args[]){ double amount = 1100; if (amount > 1000) { System.out.println("The amount is greater than 1000: "+ amount); } } }
67,605
Re-write the code below in Java to reverse the first string while preserving the order of the elements in the other strings. arr = [string1, string2, string3]
String[] arr = {"string1", "string2", "string3"}; String temp = arr[0]; arr[0] = new StringBuilder(temp).reverse().toString(); System.out.println(Arrays.toString(arr));
67,644
Implement a Java program to search the title of books in a library.
public class LibrarySearch { private ArrayList<String> titles; public LibrarySearch() { titles = new ArrayList<String>(); } public boolean searchTitle(String title) { for (int i = 0; i < titles.size(); i++) { String titleInList = titles.get(i); if (title.eq...
67,665
Write a code snippet in Java that sorts a given array in ascending order.
public static void sortAscending(int[] arr) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } ...
67,685
Write a Java method to transform a String input into a String array with each element the length of 4. String input = "HelloWorld";
public static String[] stringToArray(String input) { String[] stringArray = new String[input.length()/4]; int count = 0; for (int i = 0; i < input.length(); i += 4) { stringArray[count] = input.substring(i, i+4); count++; } return stringArray; }
67,691
Construct a Java class to execute a binary search. public class BinarySearch { }
public class BinarySearch { int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); ...
67,732
Add the following lines after the 2nd line in the given java program public class Calculator { public static void main(String args[]) { int a = 10; int b = 20; Add the following lines int c = a + b; System.out.println("Sum : "+c);
public class Calculator { public static void main(String args[]) { int a = 10; int b = 20; int c = a + b; System.out.println("Sum : "+c); } }
67,749
Create a class in Java called Student that stores four pieces of data: name, id, major, and gpa.
class Student { // data members String name; int id; String major; double gpa; // constructors Student(String name, int id, String major, double gpa) { this.name = name; this.id = id; this.major = major; this.gpa = gpa; } // m...
67,766
Explain how expression-oriented programming works in Java.
Expression-oriented programming is a programming paradigm where all commands are based on expressions. In Java, expression-oriented programming is used with Java Lambda Expressions, where an expression is executed by passing the command inside parentheses and executing that expression in the context of the method. This...
67,788
In the given snippet of code, insert a line of code to display the sum of two numbers. int a = 10; int b = 20;
int a = 10; int b = 20; System.out.println("Sum of two numbers is " + (a + b));
67,816
Assign values to the given array of length 10 and print it using a Java program.
public class PrintArray { public static void main(String[] args) { int[] array = new int[10]; for (int i = 0; i < 10; i++) { array[i] = i; } for (int i = 0; i < 10; i++) { System.out.print(array[i] + " "); } } }
67,836
Create a Javascript class for a customer address book.
class AddressBook { constructor() { this.contacts = []; } add(name, email, phone, relation) { let contact = { name, email, phone, relation }; this.contacts.push(contact); } delete(name) { this.contacts = this.contacts.filter(contact => contact.name !== name); } ...
67,858
Create a method in Java for encrypting a string using the Advanced Encryption Standard (AES).
public static String AESEncrypt(String toEncrypt) throws Exception { SecureRandom secureRandom = new SecureRandom(); byte[] keyBytes = new byte[16]; secureRandom.nextBytes(keyBytes); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes,"AES"); Cipher cipher = Cipher.getInstance("AES"); cipher...
67,869
Design a Java program to display the numbers from 1 to 100 in a tabular format.
public class Table { public static void main(String[] args) { for (int i = 1 ; i <= 100 ; i++){ System.out.println(i); if (i % 10 == 0){ System.out.println(""); } } } }
67,880
Define an interface in Java.
interface SampleInterface { // abstract method public void sampleMethod(); }
67,883
Write a Java script to filter out repeat elements in an array. [1, 2, 3, 2, 4, 4, 1]
let arr = [1, 2, 3, 2, 4, 4, 1]; let unique = [...new Set(arr)]; console.log(unique); // [1, 2, 3, 4]
67,888
Modify the given Java Program to generate the Fibonacci Series till provided number of terms. int n = 10;
public class Fibonacci { static int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } public static void main (String args[]) { int n = 10; System.out.println(fib(n)); } }
67,889
Write a class in Java with assigned variables and adequate getters and setters. ClassName: Student Variables: name (String), age (integer)
public class Student { private String name; private int age; // Getters & Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { ...
67,899
Create a Java program to read in an integer from the user and output the number doubled.
import java.util.Scanner; public class NumberDoubling { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); System.out.println("The doubled number is: " + (number * 2)); } }
67,912
Concatenate the strings in the given list using Java. list = ["hello", "world", "!"]
StringBuilder sb = new StringBuilder(); for (String str : list) { sb.append(str); } String output = sb.toString(); System.out.println(output); // prints "hello world!"
67,926
Calculate the sum of the numbers in the given array using the Java 8 Stream API. nums = [2, 4, 6, 10]
int sum = Arrays.stream(nums).sum(); System.out.println(sum); // prints 22
67,930
Implement a program in Java that reverses a string input given by the user.
import java.util.Scanner; public class ReverseString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputString = scanner.nextLine(); String reversedString = ""; for(int i = inputString.length() - 1; i >= 0; i-- ) { reversedString = reversedString + inputSt...
67,935
Suggest changes to the following Java code so that it sorts an array of strings by length. String[] data = {"Hello","Hi","Bye"}; Arrays.sort(data);
String[] data = {"Hello","Hi","Bye"}; Comparator<String> comparator = Comparator.comparingInt(String::length); Arrays.sort(data, comparator);
67,968
Write a Java code to sort the following array in ascending order [3, 6, 2, 8, 1, 9]. [3, 6, 2, 8, 1, 9]
public class SortList { public static void sort (int[] array) { int temp; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (array[j] > array[i]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } }...
67,976
Create a Java class to store a student's name, ID, and GPA.
public class Student { private String name; private int id; private Double gpa; public Student(String name, int id, Double gpa) { this.name = name; this.id = id; this.gpa = gpa; } public String getName() { return name; } public int getId() ...
67,988
Name four primitive types in Java.
The four primitive types in Java are boolean, char, float, and int.
68,008
Write a piece of code that implements a 3-way merge sort in Java.
class Mergesort { void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R...
68,038
Transform the given code from C++ to Java. int main() { std::vector<int> numbers {1, 2, 3, 4, 5}; for (const auto& number: numbers) { std::cout << number << std::endl; } return 0; }
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println(number); } } }
68,057
Compare and contrast Java and Python for developing applications.
Java and Python are both popular programming languages used for developing applications. Java is a statically typed language and requires extra effort in the form of type checking during compilation, while Python is a dynamically typed language and no type checking is required. Java is more suitable for large-scale ent...
68,063
Write code in Java to calculate the median from an array of integers. arr = [7, 22, 21, 19, 17, 24]
public double getMedian(int[] arr) { Arrays.sort(arr); int len = arr.length; double median = 0; if (len % 2 == 0) { int a = arr[len / 2]; int b = arr[(len / 2) - 1]; median = (a + b) / 2.0; } else { median = arr[len / 2]; } return m...
68,102
Write a Java method to find the index of a given string in an array of strings.
public int findIndexOfString(String[] array, String s) { for (int i=0; i<array.length; i++) { if(array[i].equals(s)) return i; } return -1; }
68,114
Create a class in Java and define two float variables and two float methods.
public class FloatExample { float var1, var2; public void setVar1(float a) { var1 = a; } public float getVar1() { return var1; } public void setVar2(float b) { var2 = b; } public float getVar2() { return var2; } }
68,115
Using Java, create a class constructor for a 3D vector.
class Vector3D { double x; double y; double z; Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } }
68,130
Using Java, make a program that finds out the smallest common denominator between two numbers. 12 and 18
public static int getSmallestCommonDenominator(int a, int b){ int gcd = 1; int smallNumber = Math.min(a, b); for(int i = 1; i <= smallNumber; i++) { if(a % i == 0 && b % i == 0) gcd = i; } int lcm = (a*b)/gcd; return lcm; }
68,133
Suggest a way to debug these lines of code. // code int i = 0; while (i<10) { i++; System.out.println("Something is wrong!"); }
One way to debug these lines of code is to add print statements before and after the loop to print the value of "i" both before and after the loop. Then, inside the loop, you can print out the value of "i" just before the ``println`` statement and you can also print out the value of ``i`` after the loop is exited. This...
68,137
Create an object-oriented program in Java which can display the current date and time.
import java.util.Date; public class DateTime { public static void main(String args[]) { Date date = new Date(); System.out.println("Current date and time is: " + date); } }
68,145
Identify and implement a sorting algorithm for the following array int[] array = {23, 10, 4, 15, 66, 28, 11};
int[] array = {23, 10, 4, 15, 66, 28, 11}; // Insertion sort for (int i = 1; i < array.length; i++) { int key = array[i]; int j = i-1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } System.out.println("Sorted array: "); for (int i...
68,171
Given a string, change the spaces between words to underscores String: "This is a string"
String str = "This is a string"; String newStr = str.replaceAll("\\s", "_"); System.out.println(newStr); // This_is_a_string
68,175
Given an array of integers and a target value, write a Java program to determine whether this array contains two elements with the given target sum. arr = [2, 4, 6, 8, 10], target = 8
boolean containsTargetSum(int[] arr, int target){ for (int i = 0; i < arr.length; i++){ for (int j = 1; j < arr.length; j++){ if (arr[i] + arr[j] == target) return true; } } return false; }
68,180
In Java, what does the "public" modifier mean for a class?
The public modifier for a class in Java means that the class is visible to all other classes, regardless of package. This means that any class can create an instance of the class, call its methods, and access its fields, as long as they have the proper access permissions.
68,205
Construct a method in Java to calculate the average of an array of numbers
public static double calculateAverage(int[] numbers) { double total = 0; for (int num : numbers) { total += num; } return total / numbers.length; }
68,207
Write a code in Java to convert any string to camel case format. String = "this_is_a_string"
""" Write a code to convert any string to camel case format in Java """ public class CamelCaseFormat { public static String toCamelCase(String s){ String[] parts = s.split("_"); String camelCaseString = ""; for (String part : parts){ camelCaseString = camelCaseString + toProperCa...
68,237
Write a Java code snippet to print out the value of the variable "num" to the console. int num = 10;
System.out.println(num);
68,389
Create a Java method that takes a string and returns the same string with all vowels replaced by asterisks (ie. "Hello" should return "H*ll*"). String s = "Hello";
public String replaceVowels(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { result += "*"; } else { result += ch; } } return result; ...
68,390
Write a for loop in Java that prints out the even numbers between 0 and 10.
for(int i = 0; i <= 10; i++){ if(i % 2 == 0){ System.out.println(i); } }
68,401
How do you compare two strings in Java?
In Java, two strings can be compared using the equals() or compareTo() methods. The equals() method returns true if the two strings have the same length and contain the same characters in the same order. The compareTo() method returns 0 if the two strings have the same length and contain the same characters in the ...
68,407
Write a Java program for computing the product of two matrixes.
public class MatrixProduct { // Method for matrix multiplication static int[][] multiplyMatrix(int[][] matrix1, int[][] matrix2) { int rowsInA = matrix1.length; int columnsInA = matrix1[0].length; // same as rows in B int columnsInB = ma...
68,428
What are the components of a class in Java?
A class in Java consists of the following components: fields (state of the object), constructors (constructs an object), methods (behavior of the object), nested classes and interfaces (classes that are associated with the class in which it is declared). The fields and methods are collectively called members of the cla...
68,431
Using Java, write the code to calculate the sum of elements in a two-dimensional array. int[][] arr = { {2, 3, 8}, {4, 5, 1}, {7, 0, 6} };
public class SumOfEle{ public static void main(String[] args) { // creating a two-dimensional array int[][] arr = { {2, 3, 8}, {4, 5, 1}, {7, 0, 6} }; // Creating an int variable to store the value. int sum = 0; for (int i...
68,437
Suggest an algorithm to search an element in a sorted array using Java.
public int binarySearch(int[] arr, int element){ int low = 0; int high = arr.length - 1; while(low <= high){ int mid = (low + high) / 2; if(arr[mid] == element) return mid; else if(arr[mid] > element) high = mid - 1; else low = mid + 1; ...
68,441
Cut and paste the following Java code snippet and add a condition to ensure that the number entered is always greater than 0. int number; Scanner in = new Scanner (System.in); number = in.nextInt ();
int number; Scanner in = new Scanner (System.in); do { number = in.nextInt (); } while (number <= 0);
68,459
Write a Java program to sort the elements of an int array in the descending order. [1, 10, 4, 2, 5, 3, 9]
public class ArraySort { public static void main(String[] args) { int array[] = {1, 10, 4, 2, 5, 3, 9}; int n = array.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (array[j] < array[j+1]) { int temp = ar...
68,474