instruction stringlengths 25 5.05k | output stringlengths 4 8.53k | __index_level_0__ int64 34 78.2k |
|---|---|---|
Write a Java program that reads an integer value N and prints all prime numbers less than N. | public class PrimeNumbers {
public static void main(String[] args) {
int N = 25;
for (int i = 2; i < N; i++) {
int count = 0;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
count++;
break;
}
}
... | 75,624 |
Write a Java program to convert a given integer value to octal. | public class Octal {
public static void main(String[] args) {
int num = 21;
String octal = Integer.toOctalString(num);
System.out.println("Octal: " + octal);
}
} | 75,630 |
What are the differences between data types int and float in Java? | In Java, data types int and float represent different levels of precision: int is for whole numbers, while float is for decimal numbers. Int has a 32-bit size, which allows for whole numbers from -2^31 to 2^31-1. Float is 32-bit and can refer to decimal values of up to seven digits. Float can also be expressed in scien... | 75,633 |
Create a switch statement to provide different output depending on the given input
Input: "5" | switch (input) {
case "5":
System.out.println("Input is 5");
break;
default:
System.out.println("No match");
break;
} | 75,678 |
Return the string "Hello world" as a response from a web service written in Java. | @GET
@Path("/helloWorld")
@Produces(MediaType.TEXT_PLAIN)
public String getHelloWorldString() {
return "Hello world";
} | 75,691 |
Code a Java program to find the area of an equilateral triangle. | import java.util.Scanner;
public class AreaOfTriangle {
public static void main(String[] args) {
double s;
double area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the side of the equilateral triangle:");
s = sc.nextDouble();
area = (Math.sqrt(3) /... | 75,708 |
Create a HashMap in Java which contains the name of fruits and their corresponding prices.
Mango - $2.4, Orange - $1.4, Apple - $3.2 | import java.util.HashMap;
public class FruitMap
{
public static void main(String args[])
{
// Creating a HashMap of fruit name
// and their corresponding prices
HashMap<String, Double> fruitMap = new HashMap<>();
// Mapping string values to double
fruitMap... | 75,745 |
Write a Java program to accept two integers and find the sum of the two numbers. | import java.util.Scanner;
public class SumIntegers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers: ");
int first = scanner.nextInt();
int second = scanner.nextInt();
int sum = first + se... | 75,765 |
Create a class in Java representing a car with two attributes, color and make. | public class Car {
private String color;
private String make;
public Car(String color, String make) {
this.color = color;
this.make = make;
}
public String getColor() {
return color;
}
public String getMake() {
return make;
}
} | 75,794 |
Write a Java method to convert a given integer to its equivalent English words | public static String intToEnglish(int input) {
// create an array of string representations of numbers 1 to 19
String[] numbers1_19 = {"one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fift... | 75,805 |
Create a Java program for solving quadratic equations. | import java.lang.Math;
public class QuadraticEquation {
public static void main(String[] args) {
double a = 1;
double b = -2;
double c = -8;
double x1, x2;
double discr = b * b - 4 * a * c;
if (discr > 0)
{
x1 = ( - b + Math.sqrt(discr)) / (2 * a);
x2 = ( - b - Math.sqrt(d... | 75,879 |
Design a Java program for computing the average of a given list of numbers.
[1, 2, 4, 5] | public static double computeAverage(int[] numbers){
int sum = 0;
for(int i=0; i<numbers.length; i++){
sum += numbers[i];
}
double average = (double)sum/numbers.length;
return average;
} | 75,881 |
Create a Java class to represent a point (x, y) in a two-dimensional space. | public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
} | 75,884 |
Find the index of the smallest element in an array of integers using Java.
[7, 9, 5, 4, 1, 3] | int minElementIndex = 0;
for(int i=0; i < array.length; i++) {
if (array[i] < array[minElementIndex]) {
minElementIndex = i;
}
} | 75,912 |
Create an algorithm in Java to print all the prime numbers between a given range. | public class PrimeNumber {
public static void main(String[] args) {
int start = 2;
int end = 50;
for(int i = start; i <= end; i++){
boolean isPrime = true;
for(int j=2; j < i; j++){
if(i % j == 0){
isPrime = false;
... | 75,916 |
Generate a 2D array with 5 rows and 6 columns in Java | int[][] array = new int[5][6]; | 75,950 |
Prepare a Java method which takes a string as an argument and returns the number of vowels in it. | public static int countVowels(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' ||
str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
return count;
} | 75,964 |
Write a Java program to convert a recursively given array of characters to a string.
['a', 'b', 'c'] | String arrayToString(char[] array) {
String s = "";
for (char c : array) {
s += c;
}
return s;
} | 75,993 |
Create a Java application to calculate the mean stock price of a company in the last 5 days.
[10.25, 11.94, 12.56, 11.13, 11.44] | public class StockPrice {
public static void main(String[] args) {
double[] stock_prices = {10.25, 11.94, 12.56, 11.13, 11.44};
double stock_price_sum = 0;
for(double stock_price : stock_price) {
stock_price_sum += stock_price;
}
double stock_price_mean = stock_price_sum / stock_prices.len... | 76,004 |
Create an array of strings in Java with three elements - "apple", "banana" and "orange". | String[] arr = {"apple", "banana", "orange"}; | 76,050 |
Explain the significance of exception handling in Java. | Exception handling is an important part of programming languages such as Java. It allows the programmer to handle errors gracefully without crashing the system, while also allowing the program to continue execution in a normal manner. By catching exceptions, a program can handle unexpected inputs or events and take nec... | 76,058 |
Design a class in Java that creates an Employee record. | public class Employee {
private String name;
private int age;
private String position;
public Employee(String name, int age, String position) {
this.name = name;
this.age = age;
this.position = position;
}
public String getName() {
return name;
}
public... | 76,059 |
Write a Java code that prints out all the even numbers in a given list.
list = [2, 3, 4, 5, 6, 7, 8] | for (int num : list) {
if (num % 2 == 0) {
System.out.println(num);
}
} | 76,115 |
Explain the difference between static and non-static methods in Java. | Static methods are methods that are associated with a class, rather than objects of that class. They can be invoked without having an instance of the class present, using the class name itself. Non-static methods are associated with objects of the class, and can only be used after instantiating an object. Additionally,... | 76,176 |
Edit the following Java program to sort a given array.
int[] array={16, 5, 1, 8, 10}; | public static void sortArray(int[] array) {
int temp;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
... | 76,209 |
Write a Java program to find the element that appears maximum number of times in an array.
int [] arr1 = {2, 8, 7, 2, 8, 2, 6} | public class MaxElement
{
public static void main(String[] args)
{
int[] arr1 = {2, 8, 7, 2, 8, 2, 6};
int count = 1;
int max_element=arr1[0];
int temp_count;
for (int i = 0; i < arr1.length; i++)
{
temp_count = 1;
for (int j = i+1; j < ... | 76,215 |
Create a Java program to count and print the distinct elements in an array.
int[] arr = {1, 2, 3, 2, 1, 4, 3, 2} | public class DistinctElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1, 4, 3, 2};
// Initialize all element with the value 0.
int[] temp = new int[arr.length];
int visited = -1;
for (int i = 0; i < arr.length; i++) {
int c... | 76,260 |
Generate a Java code snippet for declaring an empty list | List list = new ArrayList<>(); | 76,278 |
Create an expression statement in Java to check if a given number is between 10 and 20
15 | if (num >= 10 && num <= 20) {
// code
} | 76,280 |
Write a class in Java to calculate the perimeter and area of a rectangle. | public class Rectangle {
int length, width;
// Constructor
public Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
public int getPerimeter()
{
// Calculate perimeter
return 2*(length + width);
}
public i... | 76,299 |
Suggest an algorithm for checking if a given key exists in a binary search tree in Java. | // Returns true if key is present in given BST
boolean search(Node root, int key)
{
// Base Case
if (root == null)
return false;
// If key is present at root
if (root.key == key)
return true;
// Recursive calls for non-empty subtrees
boolean left = search(root.lef... | 76,306 |
Create a Java class that prints "Welcome to my program" when initialized. | public class Welcome {
public Welcome() {
System.out.println("Welcome to my program");
}
} | 76,308 |
Compile the following Java program using javac in command line.
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello World");
}
} | javac MyClass.java | 76,310 |
Generate a Java program for comparing two strings for equality. | public static boolean compareStrings(String str1, String str2) {
int str1Length = str1.length();
int str2Length = str2.length();
if (str1Length != str2Length)
return false;
for (int i=0; i<str1Length; i++){
if (str1.charAt(i) != str2.charAt(i))
return false;
}
r... | 76,332 |
Design a stack using a dynamic array in Java. | class MyStack {
int top;
int capacity;
int stack[];
// Creating stack
MyStack(int capacity)
{
this.capacity = capacity;
stack = new int[capacity];
top = -1;
}
// Adding an element on top of the stack
public void push(int item)
{
... | 76,352 |
Create a random number generator in Java that produces a random integer between 1 and 10. | public class RandomNumberGenerator {
public static int generateNumber() {
Random rand = new Random();
return rand.nextInt(10) + 1;
}
} | 76,399 |
Create a new Java thread. | Creating a new thread in Java is quite simple. The new thread can be created by extending the Thread class and overriding the run() method.
Example:
public class MyThread extends Thread {
@Override
public void run() {
// logic to be executed in the new thread
}
}
// Create the new thread
MyThread th... | 76,413 |
Find the sum of all the digits in a given number in Java.
Number: 1234 | Using a loop and mathematical operators, the sum of all the digits in a given number can be found in Java.
Example:
int number = 1234;
int sum = 0;
while(number > 0) {
int digit = number % 10;
sum += digit;
number /= 10;
}
System.out.println("The sum of all the digits is "+sum);
// Output: Th... | 76,415 |
Given a dataset containing multiple columns (Name, Class, and Subject) of 2,000 students, write a Java program to output a new dataset that only contains the "Name" and "Class" columns.
Name | Class | Subject
Adam | 1A | Math
Jane | 2B | Physics
Tom | 3A | English | String[][] newdataset = new String[2000][2];
for(int i=0; i< 2000; i++){
newdataset[i][0] = dataset[i][0]; //Name
newdataset[i][1] = dataset[i][1]; //Class
} | 76,424 |
Write a script to remove any white spaces in a text string.
The quick brown fox | String text = "The quick brown fox";
String newString = text.replaceAll("\\s+","");
System.out.println(newString); // Output: Thequickbrownfox | 76,425 |
Update the following code in Java for sorting an array
int arr[] = {10, 7, 8, 9, 1, 5}; | for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
} | 76,479 |
Develop an algorithm in Java to compute the Fibonacci sequence | static int Fibonacci(int a)
{
if (a <= 1) return a;
return Fibonacci(a - 1) + Fibonacci(a - 2);
} | 76,482 |
Rewrite the following line of code in a Java syntax.
console.log("Hello World!"); | System.out.println("Hello World!"); | 76,512 |
Construct a declaration in Java to store the coordinates of a point in 3D space. | public class point3D {
int x;
int y;
int z;
} | 76,519 |
Write a Java program to print out all possible combinations of the numbers from 0 to 9 | public class Combinations {
static void printCombinations(int[] arr, int index, int num, int reducedNum)
{
if (reducedNum < 0)
return;
if (reducedNum == 0) {
for (int i = 0; i < index; i++)
System.out.print(arr[i] + " ");
System.out.pri... | 76,531 |
Suggest an efficient way to sort the following array using Java.
[3, 4, 6, 2, 9, 8, 1] | The efficient way to sort the array using Java is to use the Quicksort algorithm which is an in-place, recursive sorting algorithm with an average time complexity of O(n log n). The Quicksort algorithm works by selecting an element as a pivot, partitioning the array around the pivot, and recursively applying the Quicks... | 76,579 |
Replace all occurence of the string 'Python' in a text with 'Java'.
This text is about Python programming. | This text is about Java programming. | 76,597 |
Compile this Java code to run on a JVM.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
} | javac HelloWorld.java | 76,657 |
Debug this Java program and make the output print "The answer is 3".
public class Debugging {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println("The answer is " + (x - y));
}
} | public class Debugging {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println("The answer is " + (x - y + 1));
}
} | 76,659 |
Create a Java program that divides two integers and rounds the result to the nearest integer.
int a = 8;
int b = 2; | public class Division {
public static void main(String[] args) {
int a = 8;
int b = 2;
double result = (double) a / b;
int roundedResult = (int) Math.round(result);
System.out.println(roundedResult);
}
} | 76,679 |
Create a program in Java for displaying all prime numbers between 1 and 100. | public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("All prime numbers between 1 and 100:");
int counter;
for (int i = 2; i <= 100; i++) {
counter = 0;
for (int num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == ... | 76,734 |
Debug the following code to check if it has any syntax errors.
for (int i = 0; i < 5; i++)
println("Hello World"); | for (int i = 0; i < 5; i++) {
System.out.println("Hello World");
} | 76,743 |
Create an algorithm in Java to search for a given value in a sorted array of integers. | public class BinarySearch {
public static double search(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (target == arr[mid]) {
return mid;
}
else if (tar... | 76,758 |
Write a Java program to sum the elements of an array except for the maximum and minimum.
Array: [1, 2, 3, 4, 5] | class Sum {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int max = arr[0];
int min = arr[0];
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (arr[i] > max) {
max = arr[i];
... | 76,760 |
Write a Java program to calculate the compound interest.
Principal (P): 1000
Time (T): 2
Rate of Interest (R): 10
Number of Compounds (N): 4 | class CompoundInterest {
static double compoundInterest(double principal, double time, double rate, double n)
{
return principal * (Math.pow((1 + rate / n), n * time));
}
public static void main(String[] args)
{
double principal = 1000;
double time = 2;
doub... | 76,763 |
List the elements of this array in console.
array = [22, 74, 12, 1] | for(int i=0; i<array.length; i++) {
System.out.println(array[i]);
} | 76,769 |
Use set operations to obtain the intersection of two given sets.
SetA = {1, 2, 3, 4}
SetB = {2, 4, 6, 8} | intSetA = new HashSet<Integer>();
intSetA.addAll(Arrays.asList(1, 2, 3, 4));
intSetB = new HashSet<Integer>();
intSetB.addAll(Arrays.asList(2, 4, 6, 8));
intSetA.retainAll(intSetB);
System.out.println("Intersection of SetA and SetB is " + intSetA);
// Output: Intersection of SetA and SetB is [2, 4] | 76,790 |
Construct an array of size 10 to store integers in Java. | int[] array = new int[10]; | 76,805 |
Write a Java code snippet to create an array of integers of length 5. | int[] intArray = new int[5]; | 76,827 |
Create a Java program to read in a number n, and print out the first n lines of Pascal's triangle.
n = 5 | import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
// Read in the number of lines
System.out.println("Enter the number of lines: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
// Print out pascal triangle
for(int line = 0; line < n; li... | 76,832 |
Write a Java statement to convert an int to float.
int x = 10; | float y = (float)x; | 76,839 |
Write a Java program to calculate the average of the following array elements [2, 5, 7, 8, 9, 10]. | public class AverageCalculation
{
public static void main(String[] args)
{
int[] inputArray = {2, 5, 7, 8, 9, 10};
double sum = 0.0;
// calculate the sum of elements
for(int i = 0; i < inputArray.length; i++) {
sum += inputArray[i];
}
// calculate th... | 76,873 |
Take two numbers as input and calculate the sum of them using a Java program.
x = 3
y = 4 | int sum = x + y;
System.out.println("The sum of the two numbers is: " + sum); | 76,884 |
How does error handling work in Java? | Error handling in Java is done using Exceptions. When something unexpected happens, a special type of object called an Exception is thrown. In Java, errors are handled by writing code to catch the Exception and resolving it. The code to handle Exceptions is usually placed in a try-catch block, which defines what to do ... | 76,887 |
Create a Java program to print the value of the mathematical expression sin(60) | public class PrintSinValue {
public static void main(String[] args) {
double angleInDegrees = 60;
double result = Math.sin(Math.toRadians(angleInDegrees));
System.out.println(result);
}
} | 76,891 |
Summarize the features and differences between Python and Java. | Python and Java are two of the most popular programming languages in the world. Python is a high-level, interpreted, general-purpose programming language while Java is a statically-typed, object-oriented language. Python is primarily used for web development, scripting and data science while Java is used for enterprise... | 76,906 |
Implement a main method for the following abstract class.
abstract class AbstractClass {
abstract void funOne();
abstract void funTwo();
} | abstract class AbstractClass {
abstract void funOne();
abstract void funTwo();
public static void main(String[] args) {
// Code goes here
}
} | 76,916 |
Change the following Java code to Swift.
public static int addTwoIntegers(int a, int b) {
return a+b;
} | func addTwoIntegers(a: Int, b: Int) -> Int {
return a + b
} | 76,922 |
Create an array in Java to store 5 integer values. | int [] numArray = new int[5]; | 76,923 |
Create a switch statement in Java to determine a given character type. | switch (characterType) {
case ‘A’ :
// do something
break;
case ‘B’ :
// do something
break;
case ‘C’ :
// do something
break;
} | 76,927 |
Sort the given array in Java [4, 9, 3, 6, 2, 1]. | int[] arr = {4, 9, 3, 6, 2, 1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
// Output: [1, 2, 3, 4, 6, 9] | 76,931 |
How can you count the number of elements in an array in Java? | In Java, you can count the number of elements in an array by using the length property of the array.
For example,
int[] arr = {1, 2, 3};
int len = arr.length;
System.out.println("Length of the array: " + len);
// Output: Length of the array: 3 | 76,932 |
Write a Java method to remove repeated elements from an array. | public static int[] removeDuplicates(int[] arr) {
int n = arr.length;
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
}
temp[j++] = arr[n-1];
int[] res = new int[j];
... | 76,944 |
Using the Java collections API, create a data structure such as a HashMap to store key-value pairs. | import java.util.HashMap;
HashMap<String, Integer> myMap = new HashMap<>();
// adding key-value pairs to the HashMap
myMap.put("Key1", 5);
myMap.put("Key2", 8);
myMap.put("Key3", 10);
// retrieving values by keys
int val1 = myMap.get("Key1");
int val2 = myMap.get("Key2");
int val3 = myMap.get("Key3");
// etc. | 76,945 |
Write a code to create an array of 10 random numbers between 0 and 1. | import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
Random rand = new Random();
float array[] = new float[10];
for(int i = 0; i < 10; i++) {
array[i] = rand.nextFloat();
}
System.out.println("Array of 10 ran... | 76,970 |
Write a Java method to return the largest element from an array of integers.
[4, 8, 3, 10, 6] | public static int getLargestElement(int[] nums){
int largest = nums[0];
for(int i = 1; i < nums.length; i++){
if(nums[i] > largest){
largest = nums[i];
}
}
return largest;
} | 76,983 |
Create a data structure in Java to store books and their associated information like ISBN, authors, etc. | class Book {
private int ISBN;
private String title;
private List<String> authors;
private int year;
public Book(int ISBN, String title, List<String> authors, int year) {
this.ISBN = ISBN;
this.title = title;
this.authors = authors;
this.year = year;
}
//getters and setters
} | 76,984 |
Using an If statement, output whether a given number is positive or negative.
int num = -25 | if (num > 0) {
System.out.println(num + " is a positive number");
} else {
System.out.println(num + " is a negative number");
} | 77,007 |
Create a class in Java for a Person object with two fields, name and age. | public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
} | 77,018 |
How do you create a new array of the same size as an existing array but with every element as 0 in Java? | int[] arr = new int[oldArray.length];
Arrays.fill(arr, 0); | 77,032 |
Create a Java class called "Dog" with a constructor and a bark() method that prints "Woof!". | public class Dog {
public Dog() {
}
public void bark() {
System.out.println("Woof!");
}
} | 77,037 |
Create a Java class to find all substrings of a given string.
String str = "Hello World" | public class SubstringFinder {
public static List<String> findSubstrings(String str) {
List<String> substrings = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String substr = str.substring(i, j);
... | 77,040 |
Create a class in Java that creates a simple calculator which will add, subtract, multiply, divide and take square root of two numbers. | public class SimpleCalculator {
public SimpleCalculator() {}
public double add(double a, double b) {
return a + b;
}
public double subtract(double a, double b) {
return a - b;
}
public double multiply(double a, double b) {
return a * b;
}
public double divide(... | 77,047 |
Edit the following Java program to add a method printMyName. The method should print your name.
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!");
printMyName();
}
public static void printMyName(){
System.out.println("John Doe");
}
} | 77,058 |
Write a Java program to produce Fibonacci numbers up to a given number | public class Fibonacci {
public static void main(String[] args) {
int limit = 10;
System.out.print("Fibonacci Series of "+limit+" numbers: ");
for(int i=0; i<limit; i++){
System.out.print(fibonacci(i)+" ");
}
}
public static int fibonacci(int number){
if... | 77,064 |
Rewrite the following Java for loop for producing the same results in a more efficient way.
int total = 0;
for (int i = 0; i < 100000000; i++) {
total += i;
} | int total = 0;
for (int i = 0; i <= 100000000-1; i+=2){
total += (i + (i + 1));
} | 77,068 |
Create a program in Java that sort a given array using bubble sort algorithm.
Array: [4, 3, 5, 2, 1] | public static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
} | 77,120 |
Create a String variable in Java and assign the value "Computer Science". | String subject = "Computer Science"; | 77,149 |
Write a Java program to print the following output: "This is a test statement". | public class Test {
public static void main(String[] args) {
System.out.println("This is a test statement");
}
} | 77,153 |
How would you create a class in Java and add a field, constructor and method? | public class MyClass {
private String field;
public MyClass(String field) {
this.field = field;
}
public void sayHello() {
System.out.println("Hello, " + field + "!");
}
} | 77,158 |
Design a Java class to store user information. | public class User {
private String name;
private int age;
private String email;
// getters and setters
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
} | 77,174 |
Compile this Java program and output the result.
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
} | $ javac HelloWorld.java
$ java HelloWorld
HelloWorld | 77,199 |
Debug the given Java program to make it print out the value of x.
public class DebugBug {
public static void main(String[] args) {
int x = 10;
print(x);
}
public static void print(int x) {
}
} | public class DebugBug {
public static void main(String[] args) {
int x = 10;
print(x);
}
public static void print(int x) {
System.out.println(x);
}
} | 77,225 |
Create a Java class called 'Rectangle' that has two properties: length and width. | public class Rectangle {
// length and width parameters
private double length;
private double width;
//Empty constructor
public Rectangle(){
}
//Initialized constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;... | 77,228 |
Explain the differences between an array and an arraylist in Java. | An array is a static data structure, while an array list is a dynamic data structure. An array has a fixed size which cannot be changed, while an array list can be dynamically resized. Elements in an array must be of the same type, while an array list can store elements with different types. Arrays can have multiple di... | 77,241 |
Write a Java program to define a class for a Dice object. | class Dice {
private int number;
private int roll_count = 0;
Random random = new Random();
public int roll() {
roll_count++;
number = random.nextInt(6) + 1;
return number;
}
public int getNumber() {
return number;
}
public int getRollCount() {
r... | 77,294 |
How to write a try-catch statement in Java? | try {
// code to be tried
} catch (Exception e) {
// code to be executed if exception occurs
} | 77,296 |
Create a Java class named "Card" to represent a standard playing card. The class should contain a constructor which takes the card's suit and number as parameters. It should also contain two getter methods to get the suit and number of the card.
< noinput > | public class Card {
private String suit;
private int number;
public Card(String suit, int number) {
this.suit = suit;
this.number = number;
}
public String getSuit() {
return suit;
}
public int getNumber() {
return number;
}
} | 77,318 |
Check if a given string contains all the alphabets.
A quick brown fox jumps over the lazy dog | bool check = true;
string s = "A quick brown fox jumps over the lazy dog";
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < alphabet.length(); i++) {
if (!s.contains(alphabet.charAt(i)+"")) {
check = false;
break;
}
}
if (check) {
System.out.println("The given string con... | 77,355 |
What is the command for executing a code written in Java? | The command for executing a code written in Java is "java [filename]". | 77,364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.