instruction stringlengths 25 5.05k | output stringlengths 4 8.53k | __index_level_0__ int64 34 78.2k |
|---|---|---|
Write a Java code to calculate the maximum value in an array. | public static int getMax(int[] array) {
int max = array[0];
for (int i=1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
} | 59,230 |
How can you declare a new array in Java? | In Java, you can declare a new array using the following syntax: int[] arrayName = new int[arraySize]; | 59,279 |
Write a code in Java to replace all the occurrences of a given value (5) in an array with a new value (10).
arr = [2, 5, 1, 5, 8] | for (int i = 0; i < arr.length; i++) {
if (arr[i] == 5)
arr[i] = 10;
} | 59,282 |
Compile this Java program to determine any compile-time errors.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello , World");
}
} | No compile-time error. | 59,322 |
Generate Java code to display a message on a GUI. | import javax.swing.JOptionPane;
public class DisplayMessage {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello world!", "Message", JOptionPane.INFORMATION_MESSAGE);
}
} | 59,333 |
Calculate the sum of the first 10 Fibonacci numbers in Java. | 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 num = 10, sum = 0;
for (int i = 1; i <= num; i++)
{
sum += fib(i);
}
... | 59,338 |
Explain how can one sort a list of strings alphabetically in Java. | One can use the Collections.sort() method to perform an alphabetical sort of a list of strings in Java. For example, List<String> myList = new ArrayList<String>(); myList.add("Joe"); myList.add("Bob"); myList.add("Tom"); Collections.sort(myList); This will sort the strings alphabetically in the list. | 59,386 |
Generate a for loop in Java to display all the numbers between 1 and 10. | for (int i = 1; i <= 10; i++) {
System.out.println(i);
} | 59,394 |
Implement an Insertion Sort algorithm in Java. | public static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int currentElement = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > currentElement) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = currentElement;
}
} | 59,416 |
In a Java program, write a method to find the longest common subsequence of two strings. | public static String longestCommonSubsequence(String s1,String s2) {
int l1 = s1.length();
int l2 = s2.length();
int[][] aux = new int[l1+1][l2+1];
for (int i = 0; i < l1; i++) {
for (int j = 0; j < l2; j++) {
if (s1.charAt(i) == s2.charAt(j))
aux[i+1][j+1] = aux[i][j] + 1;
... | 59,422 |
Identify the correct output of this Java program given the input.
Input: Hello | Hello | 59,456 |
What is the output of this Java program?
public class Main {
public static void main(String [] args) {
String name = "John";
int age = 34;
System.out.println("My name is " + name + " and I am " + age + " years old.");
}
} | My name is John and I am 34 years old. | 59,460 |
Write a Java program to read and print out the characters of a given string one by one.
Hello World | class Test
{
public static void main(String[] args)
{
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
}
} | 59,482 |
Write a Java program to generate a random number between 25 and 75. | public class RandomNumber {
public static void main(String[] args) {
// Generate a random number between 25 and 75
int max = 75;
int min = 25;
int range = max - min + 1;
int randomNumber = (int) (Math.random() * range) + min;
System.out.println(randomNumber);
}... | 59,528 |
Create a program in Java that validates an input string for containing only numbers. | public class NumberValidation {
public boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
} | 59,542 |
Translate the following C++ program into Java.
#include <iostream>
int main() {
int num1 = 0;
int num2 = 0;
int result = 0;
std::cout << "Enter two numbers separated by a space: ";
std::cin >> num1 >> num2;
result = num1 + num2;
std::cout << "The sum of " << num1 << " and " << num2
<<... | import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int result = 0;
System.out.print("Enter two numbers separated by a space: ");
num1 = scan... | 59,549 |
Create a class in Java to represent a circle with two fields for its radius and color. | public class Circle {
private double radius;
private String color;
public Circle(double r, String c)
{
this.radius = r;
this.color = c;
}
public double getRadius()
{
return this.radius;
}
public String getColor()
{
return thi... | 59,598 |
Implement a thread pool in Java. | import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
private ExecutorService executor;
public ThreadPool(int size) {
this.executor = Executors.newFixedThreadPool(size);
}
public void submit(Runnable task) {
this.executor.execute(task);
}
p... | 59,621 |
Write a Java program to check if a given number is prime.
int n = 17; | public class PrimeNumber {
public static void main(String[] args) {
int n = 17;
boolean flag = false;
for(int i = 2; i <= n/2; ++i) {
if(n % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(n ... | 59,628 |
Write a Java method to check if a numerical value is within a specified range. | public static boolean isWithinRange(int val, int min, int max) {
return (val >= min && val <= max);
} | 59,663 |
Suggest a way to finish the following instruction.
Create a Java program to | Create a Java program to calculate the sum of all the elements in an array. | 59,666 |
Create a for loop in Java using the given array.
int[] nums = {2, 4, 8, 16, 32}; | for (int i = 0; i < nums.length; i++) {
int num = nums[i];
System.out.println(num);
} | 59,698 |
Use Java's built-in sorting algorithm and write a code that sorts a list in ascending order.
List = [5, 10, 1, 8] | import java.util.ArrayList;
import java.util.Collections;
public class SortListAscending {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(10);
list.add(1);
list.add(8);
Collections.sort(list);
Sys... | 59,712 |
What is the correct way to find the length of an array in Java? | The correct way to find the length of an array in Java is to use the length field of the array.
For example:
int[] arr = new int[10];
int len = arr.length;
// len is now 10 | 59,780 |
Merge the following two sorted arrays into a single sorted array in Java.
[1, 5, 8]
[2, 3, 6] | int[] mergeArrays(int[] array1, int[] array2) {
int[] mergedArray = new int[array1.length + array2.length];
int index1 = 0, index2 = 0;
for (int i = 0; i < mergedArray.length; i++) {
if (index1 < array1.length
&& (index2 >= array2.length || array1[index1] < array2[index2])) {
... | 59,836 |
What is the difference between an array and a list in Java? | Array is a data structure that stores elements of the same data type. It is a fixed length structure and once declared, the length of the array cannot be modified. A list is a data structure that stores elements of different types. The size of a list can be modified by adding or removing elements. Lists are more powerf... | 59,837 |
Write a Java program that displays the area of a triangle, given the three sides.
3, 4, 5 | public class TriangleArea {
public static void main(String[] args) {
int a = 3;
int b = 4;
int c = 5;
// calculate the semi-perimeter
double s = (a + b + c) / 2;
// calculate the area
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
// display the result
System.out.println("The are... | 59,862 |
Create a Java program that reads an array of integers from the console and prints out the largest number. | import java.util.Scanner;
public class LargestNum {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Input the size of array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Input "+n+" elements ... | 59,869 |
List the different access modifiers in Java | The access modifiers in Java are public, private, protected, and default. Public members are accessible everywhere and can be inherited. Private members can only be accessed within the same class. Protected members are accessible within the same package but can be inherited to a subclass in a different package. Default... | 59,891 |
Create an algorithm in Java to sort an array in descending order.
array = [10, 15, 7, 2, 13, 18] | public static void sortDesc(int[] array) {
for(int i = 0; i < array.length; i++) {
for(int j = 1; j < array.length; j++) {
if(array[j-1] < array[j]) {
int temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
} | 59,898 |
Create a class in Java for a circle. | class Circle{
double radius;
public Circle(double r){
this.radius = r;
}
public double getArea(){
return Math.PI*radius*radius;
}
} | 59,921 |
Develop a Java method to calculate the square root of a given number n. | public static double sqrt(double n) {
if (n <= 0);
return 0;
double g = n;
while (Math.abs(g*g - n) > 0.01) {
g = (g + n / g) / 2.0;
}
return g;
} | 59,947 |
Compute the maximum of the following integers using Java.
[6, 3, 8, 4, 7] | public static int findMax(int[] arr){
int max = arr[0];
for(int i = 1; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
} | 59,973 |
Edit the givenjava program to print the count of a specified character.
public class Main
{
public static void main(String[] args)
{
String str = "codersarts";
System.out.println("Number of s in the given string: " + str);
}
} | public class Main
{
public static void main(String[] args)
{
String str = "codersarts";
int count = 0;
for (int i=0; i<str.length(); i++)
{
if (str.charAt(i) == 's')
{
count++;
}
}
System.out.println("Number of s in the given string: " + count);
}
} | 60,008 |
Create a Java program to convert an array of integers into an integer.
[1,2,3,4] | public static int convertToInt(int[] arr) {
int result = 0;
for (int i=0; i<arr.length; i++) {
result += arr[i]*Math.pow(10, arr.length-1-i);
}
return result;
} | 60,098 |
Recreate the following code using Java.
def get_person(name):
person = {"name":name}
return person | public class Person{
public String name;
public Person(String name){
this.name = name;
}
public static Person getPerson(String name){
Person person = new Person(name);
return person;
}
} | 60,103 |
Find the average of a given list of numbers in Java.
int[] numbers = {2, 4, 6}; | int sum = 0;
for (int number : numbers) {
sum += number;
}
int average = sum / numbers.length; | 60,166 |
What is the purpose of declaring an enum in Java? | The purpose of declaring an enum in Java is to clearly identify a set of related constants that can be tracked. Enums are used to define a special type that contains a fixed set of constants. Enums provide type safety and make the code more self-documenting. They also make it easier for the compiler to check for correc... | 60,175 |
Write a Java program to find the common elements between two arrays.
int[] arr1 = {1, 2, 3, 4, 5}
int[] arr2 = {2, 5, 6, 7} | import java.util.Arrays;
public class CommonElements {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {2, 5, 6, 7};
for(int i=0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++)
if(arr1[i] == arr2[j])... | 60,187 |
Write a Java program to read an array of strings and sort them lexicographically (alphabetically).
String[] arr = {"apple", "cat", "hello"}; | import java.util.Arrays;
public class SortStrings {
public static void main(String[] args) {
String[] arr = {"apple", "cat", "hello"};
Arrays.sort(arr);
for(String s: arr){
System.out.println(s);
}
}
}
// Output:
apple
cat
hello | 60,188 |
Create a Java program to find the maximum element of an array.
arr = [2, 3, 1, 4, 5] | public class Maximum {
public static int findMax(int[] arr) {
int max = arr[0];
for(int i = 1; i < arr.length; i++) {
if(arr[i] > max)
max = arr[i];
}
return max;
}
public static void main(String args[]) {
int arr[] = {2, 3, 1, 4, 5};
int max = findMax(arr);
System.out.println("Maximum Element:... | 60,201 |
Create a class in Java and set its variable members.
Class Name: Student
Variables:
- name: String
- dob: Date
- rollNo: int | public class Student {
private String name;
private Date dob;
private int rollNo;
public Student(String name, Date dob, int rollNo) {
this.name = name;
this.dob = dob;
this.rollNo = rollNo;
}
} | 60,228 |
Create a Recursive Function to print out the Fibonacci numbers.
Number: 10 | public static int fibonacci(int n)
{
if (n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
// Print first 10 numbers of the fibonacci sequence
for (int i = 0; i < 10; i++)
System.out.println(fibonacci(i)); | 60,230 |
Convert this python code into Java code
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i % 2 == 0:
print(i) | int[] my_list = {1,2,3,4,5};
for(int i : my_list){
if(i % 2 == 0)
System.out.println(i);
} | 60,243 |
Edit the following line of code in a Java program to calculate the sum of all elements in an array.
int sum = 0;
for int i = 0; i < nums.length; i-- | int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
} | 60,318 |
Develop a Java program to rotate a two-dimensional array clockwise by 90 degrees.
[[1, 2],
[3, 4]] | public class RotateMatrix
{
public static void rotate(int[][] arr, int n)
{
for (int x = 0; x < n/2; x++)
{
for (int y = x; y < n-x-1; y++)
{
int temp = arr[x][y];
arr[x][y] = arr[y][n-1-x];
arr[y][n-1-x] =... | 60,348 |
Write a Java program to convert a binary string to a decimal number. | public class BinaryToDecimal {
public static int binToDecimal(String binaryNumber)
{
int decimal = 0;
int power = 0;
for(int i = binaryNumber.length() - 1; i >= 0; i--)
{
if (binaryNumber.charAt(i) == '1')
decimal += Math.pow(2, power);
power++;
}
return decimal;
}
} | 60,349 |
Write a Java method that takes a string and returns a copy of the string with all lowercase letters replaced with uppercase letters.
mixed case | public static String toUpperCase(String s) {
return s.toUpperCase();
} | 60,357 |
Write a Java program to add two large numbers of any length.
12345 and 54321 | public static String addTwoLargeNumbers(String num1, String num2) {
String result= "";
// make sure num1 is negative and num2 is positive
if (compareNumSize(num1, num2) < 0)
return addTwoLargeNumbers(num2, num1);
// variables to maintain the carry
int carry = 0;
// traver... | 60,359 |
Using the Java stream API, create a program that takes a list of integers and returns the number that appears most often in the list.
[1, 3, 3, 3, 4, 5, 5, 5, 6] | import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public static int getMostFrequentNumber(List<Integer> list) {
return list.stream()
.collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByV... | 60,371 |
Create a class in Java that takes two arguments, a name of type String and an id of type int. | public class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
} | 60,373 |
Rewrite the following in-place insertion sort algorithm in Java. | public class InsertionSort {
public static void inplaceInsertionSort(int[] array) {
// Iterate over array elements
for (int i = 1; i < array.length; i++) {
int value = array[i];
int j = i;
// Check whether the adjacent element in
// left side is greater or not
while (j > 0 && array[j - 1] > ... | 60,396 |
What is the syntax for declaring a constant in Java? | In Java, the syntax for declaring a constant is
public static final <data-type> <constant-name> = <value>; | 60,419 |
Output the number of items in a hashmap with key-value pairs ["Mon", "Monday"], ["Tue", "Tuesday"], and ["Wed", "Wednesday"]. | //Create a hashmap
HashMap<String, String> map = new HashMap<String, String>();
map.put("Mon", "Monday");
map.put("Tue", "Tuesday");
map.put("Wed", "Wednesday");
// Output the number of items in the hashmap
System.out.println("Number of items in the hashmap: " + map.size()); // Outputs 3 | 60,420 |
Edit the following Java program to output the sum of the two numbers.
int firstnum = 5;
int secondnum = 10; | int firstnum = 5;
int secondnum = 10;
int sum = firstnum + secondnum;
System.out.println("The sum of the two numbers is: " + sum); | 60,425 |
Create an array of strings in Java. | String[] myArray = {"Hello", "World", "Foo", "Bar"}; | 60,426 |
Using Java, create a method that takes an array of integers and returns the maximum value. | public static int getMaxValue(int[] array) {
int maxValue = array[0];
for(int i=1; i < array.length; i++) {
if(array[i] > maxValue)
maxValue = array[i];
}
return maxValue;
} | 60,429 |
Write a Java program that takes the following input parameters and prints their sum to the console.
int a = 2; int b = 4; | public class Sum {
public static void main(String[] args) {
int a = 2;
int b = 4;
int sum = a + b;
System.out.println("Sum = " + sum);
}
} | 60,441 |
Write a Java program to sort the following array of integers using Quick Sort.
int arr[] = {4, 3, 6, 2, 5, 1}; | public class QuickSort
{
// Method to implement quick sort
public static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
... | 60,444 |
Compute the sum of all the elements in an array of integers in Java.
int[] arr = {1,2,3,4,5}; | int sum = 0;
for (int i=0; i<arr.length; i++) {
sum += arr[i];
}
System.out.println(sum); | 60,449 |
Describe the role of the constructors in a Java class. | The role of the constructors in a Java class is to initialize the fields of an object. A constructor is a special method that is called when an object is instantiated. Constructors typically have the same name as the class and take in parameters. The parameters are used to initialize the fields of the object. Construct... | 60,474 |
Create a class in Java with two methods, get and set. | public class MyClass {
private int x;
// Getter and setter
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
} | 60,495 |
How to check if a number is prime or not in Java | public class Number {
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 %... | 60,498 |
How to convert a string to a list in Java | String inputString = "TestString";
List<Character> list = new ArrayList<>();
for(char c : inputString.toCharArray()) {
list.add(c);
} | 60,503 |
Overwrite the existing Java timestamp processing class to produce the desired outputs.
public class TimestampProcessing {
public static List<String> process(String[] timestamps) {
List<String> result = new ArrayList<>();
for (String timestamp : timestamps) {
String dateFormat = "dd/MM/yy... | public class TimestampProcessing {
public static List<String> process(String[] timestamps) {
List<String> result = new ArrayList<>();
for (String timestamp : timestamps) {
String dateFormat = "dd/MM/yyyy hh:mm:ss";
Date date = new SimpleDateFormat(dateFormat).parse(timestamp)... | 60,506 |
Write a Python code to sort the given list of strings alphabetically.
lst = ["Java", "C++", "Go", "Python"] | def alphabetical_sort(lst):
lst.sort()
return lst
print(alphabetical_sort(lst)) | 60,525 |
Modify the Java program below so that it prints the sum of two given numbers.
int num1 = 3;
int num2 = 5; | int num1 = 3;
int num2 = 5;
int sum = num1 + num2;
System.out.println("Sum is: " + sum); | 60,566 |
Translate the following Array of characters into a String in Java.
['h', 'e', 'l', 'l', 'o'] | String s = new String(new char[]{'h','e','l','l','o'}); | 60,636 |
Write a code for converting a temperature from Fahrenheit to Celsius in Java. | public static double fToC(double f) {
double c = (f - 32) * (5.0/9.0);
return c;
} | 60,644 |
Create a Java method to print a two-dimensional array.
int array[3][3] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}} | public class TwoDimensionalArray {
public static void main(String args[])
{
int[][] arr = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
int m = 3;
int n = 3;
printArray(arr, m, n);
}
public static void printArray(int[... | 60,652 |
Generate a Java code to display the multiplication table from 1 to 10. | 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+"="+(i*j)+" ");
System.out.println();
}
} | 60,672 |
How would you implement stack using node in Java? | public class Stack {
private Node top;
public Stack(){
this.top = null;
}
private class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
public void push(int data){
Node newNode = new Node(data);
if(top == null... | 60,674 |
Create a loop in Java for printing all elements of an array of strings.
["String1", "String2", "String3", "String4"] | String[] strArr = {"String1", "String2", "String3", "String4"};
for (String str : strArr) {
System.out.println(str);
} | 60,675 |
What is the syntax of creating a variable in Java? | The syntax for creating a variable in Java is:
<data_type> <variable_name> = <variable_value>;
For example:
int myVar = 5; | 60,677 |
Write a code in Java for finding the factorial of a number.
5 | public class Factorial {
public static int calcFactorial(int number){
int factorial;
if(number == 0 || number == 1){
factorial = 1;
} else {
factorial = number * calcFactorial(number-1);
}
return factorial;
}
public static void main(String[] args){
System.out.println(calc... | 60,679 |
How would you check for syntax errors in a given Java code? | Syntax errors in Java code can be checked by using the Java compiler. The compiler will identify the location and reason for any syntax errors, which can then be corrected. Additionally, IDEs often have built-in syntax checkers that can highlight errors before compilation. | 60,681 |
Generate a random alphanumeric string of length 8 in Java. | String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789"
+ "abcdefghijklmnopqrstuvxyz";
StringBuilder sb = new StringBuilder(8);
for (int i = 0; i < 8; i++) {
int index
= (int)(AlphaNumericString.length()
... | 60,683 |
Create a Java object for a student with the fields 'Name' and 'Marks'. | public class Student {
// fields
String name;
int marks;
// constructor
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
// other methods
} | 60,740 |
Calculate the union of two given sets in Java.
Set 1: {1, 2, 3}
Set 2 : {3, 4, 5} | Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
Set<Integer> set2 = new HashSet<>();
set2.add(3);
set2.add(4);
set2.add(5);
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println(union); // [1, 2, 3, 4, 5] | 60,744 |
Develop a Java program that prints a given string. | public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str);
}
} | 60,811 |
Develop a program in Java to calculate the product of two numbers. | public static int product(int a, int b)
{
return (a*b);
} | 60,818 |
Implement a linear search algorithm for an array of integers in Java. | public static int linearSearch(int[] arr, int value) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
} | 60,828 |
Translate the following code from Java to Python.
public static void main (String[] args) {
int x = 5;
while (x > 0) {
System.out.println(x);
x--;
}
} | x = 5
while x > 0:
print(x)
x -= 1 | 60,830 |
Using Java, write a method that takes two strings and checks if they are anagrams of each other. | public static boolean isAnagram(String str1, String str2){
if(str1.length() != str2.length()){
return false;
}
char[] char1 = str1.toCharArray();
char[] char2 = str2.toCharArray();
Arrays.sort(char1);
Arrays.sort(char2);
return Arrays.equals(char1, char2);
} | 60,854 |
What is the correct syntax to call a constructor of a class in Java? | ClassName objectName = new ClassName(parameters); | 60,861 |
Create a method to read in input from the console in Java | import java.util.Scanner;
public static String readFromConsole(){
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
} | 60,864 |
Convert the following code to an equivalent program in Java.
def printing_number(number):
print(number) | public void printing_number(int number) {
System.out.println(number);
} | 60,892 |
Create a Java program to generate and print Fibonacci series of a given size.
Size: 8 | public class FibonacciSeries
{
public static void main(String[] args)
{
int n = 8;
int f1 = 0, f2 = 1;
System.out.print("The Fibonacci series of size "+n+" is : ");
for (int i = 1; i <= n; i++)
{
System.out.print(f1 + " ");
int next = ... | 60,938 |
What are the steps to create a constructor in Java? | The steps to create a constructor in Java are:
1. Declare a constructor with a unique name which matches the name of the class.
2. Make sure that the constructor has the same access modifier as the class.
3. Constructor parameters should align with instance variables
4. Initialize the instance variables in the body of ... | 60,946 |
What is the correct way to define a method in Java? | The correct way to define a method in Java is to use the following syntax:
modifier returnType methodName(parameter_list) {
//method body
} | 60,948 |
Create a class in Java to store student information such as name, age, and course. | public class Student {
private String name;
private int age;
private String course;
public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}
public String getName() {
return name;
}
public int getAg... | 60,949 |
Edit the following Java code to print the elements of an array in the form of a matrix.
public class Matrix
{
public static void main(String[] args)
{
int[][] myArray = {{1,2,3},
{4,5,6},
{7,8,9}};
}
} | public class Matrix
{
public static void main(String[] args)
{
int[][] myArray = {{1,2,3},
{4,5,6},
{7,8,9}};
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{... | 61,082 |
Use a loop in Java to print out the squares of numbers from 1 to 10. | for (int i = 1; i <= 10; i++) {
System.out.println(i * i);
} | 61,120 |
Create a Java program to print a square diamond pattern with '*' characters. | public class DiamondPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
fo... | 61,123 |
Create an array of 10 elements using Java. | int[] array = new int[10]; | 61,166 |
Generate a Java program that prints the longest word in a sentence
Hello my name is John | public class longestWord{
public static void main(String[] args) {
String inputStr = "Hello my name is John";
String[] words = inputStr.split(" ");
String longestWord = "";
int maxLength = 0;
for (String w : words){
if (w.length() > maxLength) {
maxLength = w.length();
... | 61,197 |
Develop a Java program to calculate the average of three numbers | public class AverageCalculator {
public static void main(String[] args)
{
float num1 = 10.7f;
float num2 = | 61,202 |
Create a for loop in Java to find the sum of the first 20 numbers. | int sum = 0;
for (int i=1; i <= 20; i++){
sum = sum + i;
}
System.out.printf("The sum of the first 20 numbers is %d", sum); | 61,203 |
Write a Java program to print the Fibonacci sequence up to the limit of n.
n = 10 | public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int num1=0, num2=1;
System.out.print("Fibonacci Series of "+n+" numbers:");
for (int i = 1; i <= n; ++i) {
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
... | 61,215 |
Write a Java method to insert a given string at the beginning of every word in a given sentence.
String sentence = "The quick brown fox jumps over the lazy dog"; | String addPrefix(String sentence, String prefix) {
String[] words = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word: words) {
sb.append(prefix + word + " ");
}
return sb.toString();
}
addPrefix(sentence, "The"); // Output: "TheThe quick Thebrown Thefox Thejumps Theov... | 61,240 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.