instruction stringlengths 25 5.05k | output stringlengths 4 8.53k | __index_level_0__ int64 34 78.2k |
|---|---|---|
Create a class called "BankAccount" in Java with instance variables for the account number, name, and balance. | public class BankAccount {
private int accountNumber;
private String name;
private double balance;
// Getter and setter methods
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;... | 61,250 |
Construct a loop in Java to traverse over all elements of an array
int[] numbers = {5, 7, 9, 22}; | for(int i = 0; i < numbers.length; i++){
int element = numbers[i];
// execute code here
} | 61,312 |
Write a Java method that takes two numbers and returns the sum of them. | public static int addNumbers(int a, int b) {
return a + b;
} | 61,347 |
You need to write a script in Java to reverse a given list of Strings.
list = ["John", "Alice", "Bob"] | public class ReverseList {
public static void reverseList(List<String> list)
{
if (list.size() > 1) {
String temp = list.get(0);
list.remove(0);
reverseList(list);
list.add(temp);
}
}
public static void main(String[] args)
{
... | 61,361 |
Write Java code for converting a string to an array.
String: "Hello" | String[] strArray = {"H", "e", "l", "l", "o"}; | 61,430 |
Write a Java program to create a thread which prints the numbers from 10 to 0 after every 2 seconds. | public class MyThread extends Thread {
public void run() {
for(int i = 10; i >= 0; i--) {
System.out.println(i);
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {
//Do nothing
}
}
}
} | 61,441 |
Write a Java program to compare two strings lexicographically.
Two strings: string1="GeeksforGeeks" and string2="GeeksQuiz" | public class CompareStringLexicographically {
public static void main(String[] args)
{
String str1 = "GeeksforGeeks";
String str2 = "GeeksQuiz";
// Comparing both strings lexicographically
int result = str1.compareTo(str2);
// checking for the comparison outp... | 61,461 |
Implement a simple password validator in Java.
password = "Password1" | public class PasswordValidator {
public static boolean validate(String password) {
if (password.length() < 8) {
return false;
}
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for (int i = 0; i < passwor... | 61,491 |
Write a code in Java to find all the prime numbers between 0 and n. | public static List<Integer> findPrimes(int n) {
List<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if ... | 61,501 |
How do you use exceptions to cleanly exit from a method in Java? | To use exceptions to cleanly exit from a method in Java, you should throw an exception at the end of the method body. Exceptions can be used to indicate unusual situations and can be used to terminate a method execution if desired. To throw an exception, you use the following syntax:
throw new Exception("Exception Mes... | 61,505 |
Replace the last occurrence of a given word in a string.
str = "Welcome to the world of Python"
word = "Python" | updated_str = str.rsplit('Python',1)[0] + 'Java'
The updated string is "Welcome to the world of Java". | 61,509 |
Create an array in Java that contains five elements each of type String. | String[] arr = {"String 1", "String 2", "String 3", "String 4", "String 5"}; | 61,584 |
Could you suggest a method written in Java for finding the average of a set of numbers?
Numbers = [10, 20, 5, 15] | public static double getAverage(int[] Numbers){
double sum = 0;
for(int num : Numbers){
sum += num;
}
double average = sum / Numbers.length;
return average;
} | 61,593 |
How can you let a user input a character in a Java program? | You can let a user input a character in a Java program using the Scanner class. For example, you can use the next().charAt(0) method to let a user input a character. | 61,643 |
Find the intersection of two sorted arrays in Java.
arr1=[1, 2, 4, 5, 6]
arr2=[2, 3, 5, 7] | public static int[] intersection(int[] arr1, int[] arr2)
{
// Initialise array to store intersection
int[] result = new int[arr1.length];
// Initialise two index in both array
int i = 0, j = 0;
// Initially set intersection index
int k = 0;
// Sort both array
Arrays.sor... | 61,675 |
Create a Java program that takes two numbers and prints out the larger number.
Number 1: 6
Number 2: 8 | public class Program {
public static void main(String[] args) {
int num1 = 6;
int num2 = 8;
if (num1 > num2) {
System.out.println(num1);
} else {
System.out.println(num2);
}
}
} | 61,678 |
Edit the following Java program and make it compile without any errors.
public class Main {
public static void main(String[] args) {
System.print("Hello, World!");
}
} | public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
} | 61,698 |
Rewrite the below JAVA program in Python
public static void main (String[] args) {
int count = 10;
while (count > 0) {
System.out.println("Code:" + count);
count--;
}
} | count = 10
while count > 0:
print("Code:", count)
count -= 1 | 61,701 |
Write a JAVA program to display the list of numbers from 1 to 10 | public class NumberList {
public static void main(String[] args)
{
// Printing numbers from 1 to 10
for (int num = 1; num <= 10; num++)
System.out.println(num);
}
} | 61,704 |
Write a Java code to perform linear search on the given array. | public class LinearSearch
{
/**
* Linear search implementation
*
* @param arr the array of elements to search
* @param target the element to search for
* @return the index of the element if found, -1 otherwise
*/
public static int linearSearch(int[] arr, int target)
{
... | 61,715 |
Create a class in Java to store student details
Attributes: id (int), name (String), grade (int) | public class Student{
// Attributes
private int id;
private String name;
private int grade;
// Constructor
public Student(int id, String name, int grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getters and setters
public int getI... | 61,755 |
In Java, write a method that reverses an array of integers. | public static int[] reverseArray(int[] arr)
{
int[] reversed = new int[arr.length];
int j = 0;
for (int i = arr.length - 1; i >= 0; i--) {
reversed[j++] = arr[i];
}
return reversed;
} | 61,777 |
In Java, write a method that wraps a given string into a paragraph with each line no longer than the given number of characters. | public static String wrapText(String text, int maxCharsPerLine)
{
// Create a StringBuilder for formulating the output
StringBuilder result = new StringBuilder();
// Break the given text into individual lines, each containing no more than maxCharsPerLine characters
String line = "";
int index = ... | 61,778 |
Complete the following Javascript code to filter out all numbers divisible by 3.
const numbers = [1,2,3,4,5,6,7,8,9];
const result = | const numbers = [1,2,3,4,5,6,7,8,9];
const result = numbers.filter(num => num % 3 !== 0); | 61,794 |
Show how to find the mean of three numbers in Java.
int x = 3; int y = 4; int z = 5; | public class MeanCalculator {
public static void main(String args[]){
int x = 3; int y = 4; int z = 5;
double mean = (x + y + z) / 3.0;
System.out.println("The mean of the three numbers is: " + mean);
}
} | 61,813 |
Write Java code to check if two strings are anagrams, e.g. god, dog are anagrams.
String str1 = "abc";
String str2 = "cba"; | public static boolean isAnagram(String str1, String str2)
{
char arr1[] = str1.toCharArray();
char arr2[] = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
} | 61,874 |
Design a Java class to store the details of a customer. | public class Customer {
private String name;
private String address;
private String email;
private String phone;
public Customer() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress(... | 61,898 |
Create a class called “Car” in Java with the following attributes and methods. | public class Car {
private String make;
private String model;
private int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = ma... | 61,905 |
Using Java, create a program to find the highest value in this array.
arr = [1, 2, 4, 7, 10] | public class HighestValue {
public static int findHighest(int[] arr) {
int highest = arr[0];
for (int i = 1; i < arr.length; i++) {
highest = Math.max(highest, arr[i]);
}
return highest;
}
public static void main(String[] args) {
int[] arr = {1, 2, 4, 7, 10};
System.out.println... | 61,936 |
Generate HTML element using Javascript.
Tag name: p | let p_element = document.createElement('p'); | 61,998 |
Use class inheritance to create an object in Java. | // Base class
class Vehicle
{
String brand = "Ford";
public void honk()
{
System.out.println("Tuut, tuut!");
}
}
// sub class
class Car extends Vehicle
{
String modelName = "Mustang";
public static void main(String[] args)
{
// Create an object of Car
Car myCar ... | 61,999 |
Create a while loop in Java to break at the first even number found. | int i = 0;
while (i <= 10) {
if (i % 2 == 0) {
break;
}
i++;
} | 62,001 |
Convert this C code to Java.
int addTwoNumbers(int a, int b)
{
return a + b;
} | public int addTwoNumbers(int a, int b)
{
return a + b;
} | 62,004 |
Find the minimum number from the given array in Java.
int arr[]={10, 50, 18, 63, 27}; | int min = arr[0];
for (int i = 1; i < arr.length; i++)
if (arr[i] < min)
min = arr[i];
System.out.println(min); | 62,036 |
Write a Java program to display a pattern of numbers. | class PatternTest
{
public static void main(String[] args)
{
int[][] pattern = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for (int i=0; i<pattern.length; i++)
{
for (int j=0; j<pattern[i].length; j++)
{
System.out... | 62,048 |
Given the following Java code, can you spot the error?
public class MyClass {
int x = 10;
int y = 20;
public static int add(int x, int y) {
int sum = x + y;
return sum;
}
} | The method add() is a static method and cannot directly access the instance variables x and y. The error can be fixed by passing in the two parameters x and y to the add() method:
public static int add(int x, int y) {
int sum = x + y;
return sum;
} | 62,085 |
Write a Java code snippet to print the following line of text: “Hello, World!” | System.out.println("Hello, World!"); | 62,118 |
Write a Java method that takes in a string and returns an array containing all the possible permutations of this string. | public static ArrayList<String> allPermutations(String inputString){
ArrayList<String> permutations = new ArrayList<>();
if (inputString.length() == 0) {
permutations.add("");
return permutations;
}
char first = inputString.charAt(0);
String remainder = inputString.substring(1);
... | 62,134 |
Create a program in Java to reverse a sentence.
This is a sample sentence. | String input = "This is a sample sentence";
String reversed = new StringBuffer(input)
.reverse()
.toString();
System.out.println(reversed); | 62,144 |
Create a Java code snippet that takes two integers as parameters and prints the larger one. | public static void printMax(int a, int b) {
if (a > b)
System.out.println(a);
else
System.out.println(b);
} | 62,150 |
Create a program in Java to check whether the given word is a palindrome or not.
"radar" | public class Palindrome{
public static boolean checkPalindrome(String str){
int i=0,j=str.length()-1;
while(i<j){
if(str.charAt(i) != str.charAt(j))
return false;
i++;j--;
}
return true;
}
} | 62,254 |
Create a conditional statement in Java that prints "Welcome!" if the given argument is "Hi".
"Hi" | if (argument.equals("Hi")) {
System.out.println("Welcome!");
} | 62,256 |
Write a class in Java that prints out the nth number of the Fibonacci sequence using recursion.
6 | public class Fibonacci {
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
... | 62,279 |
Compose a Java program to print a given pattern on the screen.
N = 5 | public class Pattern {
public static void main(String[] args) {
int N = 5;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(Math.abs(i-j)+1 + " ");
}
System.out.println();
}
}
}
// Output
1 2 3 4 5
2 1 2 3... | 62,294 |
Compose a Java program that finds the factorial of a number.
n = 5 | public class Factorial {
public static void main(String[] args) {
int n = 5;
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
}
System.out.println(result);
}
} | 62,301 |
Create a Java program to list out all prime numbers between 1 and n.
n = 20 | public class AllPrimeNumbers
{
public static void main(String args[])
{
int n = 20;
System.out.print("All Prime Numbers between 1 and " + n + " are: ");
for (int i = 2; i <= n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j... | 62,304 |
What is the maximum value of an integer in Java? | In Java, the maximum value of an integer is 2147483647. | 62,309 |
Design a Java class for representing a stack data structure. | public class MyStack {
int top;
int[] stackArray;
// Constructor to initialize
public MyStack(int capacity) {
stackArray = new int[capacity];
top = -1;
}
// Push an element to the top of the stack
public void push(int data) {
stackArray[++top] = data;
... | 62,315 |
Using Java, write a program to sort a provided array of integers in ascending order.
[2, 5, 3, 1, 9, 4] | public class SortIntArray{
public static void main(String[] args) {
int[] intArray = {2, 5, 3, 1, 9, 4};
Arrays.sort(intArray);
System.out.println("Sorted elements are:");
for(int i : intArray){
System.out.println(i);
}
}
} | 62,316 |
Write a Java program to print 'Hello World' five times. | public class HelloWorld {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println("Hello World");
}
}
} | 62,340 |
Write a Java program that searches an array for a given value and returns the index at which it is found.
int[] arr = {3, 4, 6, 7, 8, 10};
int searchValue = 8; | public static int searchArray(int[] arr, int searchValue) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == searchValue) {
return i;
}
}
return -1;
} | 62,371 |
Construct a Java switch statement to check whether a given number is positive, negative, or zero.
Number: -7 | int number = -7;
switch (number) {
case 0:
System.out.println("Zero");
break;
case > 0:
System.out.println("Positive");
break;
case < 0:
System.out.println("Negative");
break;
} | 62,440 |
Write a Java program to replace the first occurrence of a given character with '*'.
String = "Hello World!"
Character = 'o' | String str = "Hello World!";
String newStr = str.replaceFirst("o", "*");
System.out.println(newStr); | 62,511 |
Write a Java program to print out a triangle of stars.
3 | *
**
*** | 62,514 |
Provide an answer to the following question
What is the maximum size of an array in Java? | The maximum size of an array in Java is determined by the amount of memory that the JVM has available to allocate. In practice, this means that the maximum size of an array is typically limited to the amount of free memory available on the heap. Generally speaking, the maximum size of an array can range from a few thou... | 62,545 |
Write Java code to calculate the sum of first n natural numbers. | public class SumNatural {
public static void main(String[] args) {
int num = 20, sum = 0;
for(int i = 1; i <= num; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
} | 62,586 |
Write code in Java to print all the unique elements in an array. | public void printUnique(int[] array) {
Set<Integer> set = new HashSet<>();
for (int i : array) {
set.add(i);
}
System.out.println(set);
} | 62,591 |
Write a short Java program to generate a random value from 1 to 10. | import java.util.Random;
public class genRandom {
public static void main(String[] args) {
// create instance of Random class
Random rand = new Random();
// Generate random integers in range 0 to 10
int randomNum = rand.nextInt(11);
// Print random integers
System.out.println("... | 62,594 |
Create a Java program that takes two strings s and t as input and checks if t is an anagram of s
s = "abc", t = "bac" | public class Anagram {
static void isAnagram(String s1, String s2) {
// Removing all white spaces from s1 and s2
String copyOfs1 = s1.replaceAll("\\s", "");
String copyOfs2 = s2.replaceAll("\\s", "");
// Initially setting status as true
boolean status = true;
... | 62,602 |
Write a Java program to filter out the common characters in two given strings. | public static String filterCommonCharacters(String str1, String str2) {
StringBuilder sb = new StringBuilder();
// Traverse both strings
for (int i = 0; i < str1.length(); i++) {
// Check if str2 contains str1[i]
boolean found = false;
for (int j = 0; j < str2.length(); j++) {
... | 62,616 |
Create a Java method which takes a String and an integer as inputs and concatenates the integer to the beginning of the string.
inputString: "This is a test"
num: 38 | public static String prependIntToString(String inputString, int num) {
String outputString = num + "" + inputString;
return outputString;
} | 62,617 |
Write a Java method that takes a string and an integer as input, and returns the string in reverse with the integer repeated at the end.
inputString: "Hello"
num: 3 | public static String repeatNumAtEnd(String inputString, int num) {
String outputString = "";
for(int i = inputString.length() - 1; i >= 0; i--){
outputString += inputString.charAt(i);
}
for (int i = 0; i < num; i++){
outputString += num;
}
return outputString;
} | 62,622 |
Write a Java method to replace all spaces from a given string with a provided character
Hello World!
Z | public static String replaceCharacter(String str, char c) {
return str.replaceAll(" ", String.valueOf(c));
}
System.out.println(replaceCharacter("Hello World!", 'Z')); // Output: HelloZWorld! | 62,643 |
Create an object-oriented program in Java to calculate the area of a rectangle. | public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height){
this.width = width;
this.height = height;
}
public int calculateArea(){
return this.width * this.height;
}
} | 62,666 |
Create a Java method to print a binary tree in level order. | public class BinaryTree {
// Root of Binary Tree
Node root;
// Function to print binary tree in level order
void printLevelOrder() {
int h = height(root);
int i;
for (i = 1; i <= h; i++)
levelOrder(root, i);
}
// Print nodes at a given level... | 62,689 |
Create a method to validate an email address in Java. | public static boolean isValidEmail(String str) {
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
Pattern pat = Pattern.compile(emailRegex);
if (str == null)
re... | 62,696 |
Compile the following Java program.
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello, World");
}
} | javac HelloWorld.java | 62,752 |
Generate a Java program that creates a random array of 10 integers ranging from 0 to 9. | import java.util.Random;
class GenerateRandomArray{
public static void main(String[] args)
{
int[] arr = new int[10];
Random random = new Random();
for (int i=0; i<arr.length; i++){
arr[i] = random.nextInt(10);
}
// print the elements
for (int i=0... | 62,761 |
Given an array of integers, write a Java method to find the largest three numbers.
[3, 5, 9, 4, 8, 6, 1] | public static void largestThreeNumbers(int[] numbers) {
Arrays.sort(numbers);
int size = numbers.length;
System.out.println("Largest three numbers: "
+ numbers[size-1] + " "
+ numbers[size-2] + " "
+ numbers[size-3]);
} | 62,763 |
Write a method in Java that takes a string as input and returns its length. | public static int getStringLength(String str)
{
// Return the length of the string
return str.length();
} | 62,803 |
Create a Java program that calculates the probability of rolling a pair of dice and getting the number 8. | public static double calculateProbability(int target) {
int numFavorableOutcomes = 0;
int numTotalOutcomes = 36;
for (int i = 1; i <=6; i++) {
for (int j = 1; j <= 6; j++) {
if (i + j == target) {
numFavorableOutcomes++;
}
}
}
return (double) n... | 62,806 |
Write a Java Program to print the Fibonacci numbers for a given range. | public class Fibonacci {
public static void main(String[] args) {
int range = 10;
int i = 0;
int fibo = 0;
int fibo1 = 1;
int fibo2 = 1;
while(i <= range) {
System.out.print(fibo + " ");
fibo = fibo1 + fibo2;
fibo1 = fib... | 62,813 |
Construct a regex in Java that matches a valid email address. | String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; | 62,833 |
Write Java code to generate a matrix of size n.
n = 5 | public static int[][] generateMatrix(int n){
int[][] matrix = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
matrix[i][j] = i * n + j;
}
}
return matrix;
} | 62,839 |
Generate a loop that prints odd numbers between 0 to 10. | for(int i = 0; i <= 10; i++){
if(i % 2 != 0)
System.out.println(i);
} | 62,840 |
Write a java code to calculate the sum of two numbers provided as input.
int num1 = 25;
int num2 = 24; | int result = num1 + num2;
System.out.println(result); | 62,881 |
Create a class in Java that takes two parameters, "name" and "age". | public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
} | 62,898 |
Print the following statements in a sorted order
I am learning Python
I am learning Java | I am learning Java
I am learning Python | 62,909 |
Write a Java code to find the longest common prefix in a string array.
String [] arr = {"flower","flow","flight"} | public static String longestCommonPrefix(String[] arr)
{
if (arr.length == 0)
return "";
String prefix = arr[0];
for (int i = 1; i < arr.length; i++)
{
while (arr[i].indexOf(prefix) != 0)
{
prefix = prefix.substring(0, prefix.length() - 1);
... | 62,920 |
What is the syntax to convert a string to an integer in Java? | int num = Integer.parseInt(string); | 62,947 |
Implement a switch-case statement in Java. | public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
... | 62,962 |
Create a class in Java named 'Person' that has the following fields: name, age, and gender. | public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
} | 62,974 |
Describe the concept of static variables in Java. | In Java, static variables (also known as class variables) are variables that are declared with the static keyword and are available to access through the class name. These variables are shared between all objects. They are typically used for storing information that does not change between objects. | 62,982 |
Develop a Chatbot that can respond to the user's queries about programming languages. | def chatbot():
while True:
# User's query
query = input("What would you like to know about programming languages? ")
# Checking if query is relevant
if "language" in query:
# Provide response
print("There are many different programming languages, and thes... | 62,985 |
Edit the following Java program to read 5 integers from the user and display the largest one. | import java.util.*;
public class LargestOfFive {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int [] numbers = new int [5];
for(int i=0; i<5; i++) {
System.out.print("Enter an integer: ");
numbers[i] = sc.nextInt();
}
... | 63,001 |
Write a Java program to print a right triangle star pattern with a given base.
base = 4 | public class RightTrianglePattern
{
// Function to demonstrate printing pattern
public static void printPattern(int baseSize)
{
int i, j;
// outer loop to handle the number of rows
for(i=0; i<baseSize; i++)
{
// inner loop to handle number spaces
... | 63,004 |
Create a two-dimensional array in Java with values corresponding to the given output.
Output: [4, 6, 10] | int[][] arr = {{4, 6, 10}}; | 63,009 |
Develop a script in Java to generate Fibonacci numbers to nth place. | public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i)
{
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
... | 63,058 |
Create a script in Java to find the most repeated element in an array.
Array in string form: “a,b,c,d,a,a,b,d,d” | public class MaxOccurring
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
int count[] = new int[ASCII_SIZE];
int len = str.length();
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
int max = -1; // Initialize m... | 63,063 |
Write a Java code snippet to calculate the area of a triangle, given three points.
x1, y1 = 0, 0
x2, y2 = 3, 4
x3, y3 = 4, 0 | public class TriangleAreaCalculator {
// Returns the area of the given triangle, given three points
static double area(int x1, int y1, int x2, int y2, int x3, int y3){
double side1 = Math.pow(Math.abs(x1-x2),2) + Math.pow(Math.abs(y1-y2),2);
double side2 = Math.pow(Math.abs(x2-x3),2) + Math.pow... | 63,068 |
You need to write a Java program to check whether a given string is a palindrome or not. | public class Palindrome {
public static void main(String[] args) {
String a = "Madam";
String b = "";
int n = a.length();
for(int i = n - 1; i >= 0; i--) {
b = b + a.charAt(i);
}
if(a.equalsIgnoreCase(b)) {
System.out.println(... | 63,082 |
Edit the statements given below so that they can be compiled and run without any errors.
public class Test {
public static void main(String[] args) {
System.out.println("Hello World");
int x;
System.out.println(x);
}
} | public class Test {
public static void main(String[] args) {
System.out.println("Hello World");
int x = 0;
System.out.println(x);
}
} | 63,083 |
Debug this Java code to make it work.
public class test
{
public static void main(String args[])
{
int a = 5;
int b = 0;
int c = a + b;
System.out.println("Result is: " + c);
}
} | public class test
{
public static void main(String args[])
{
int a = 5;
int b = 0;
if(b!=0)
{
int c = a + b;
System.out.println("Result is: " + c);
}
else
{
System.out.println("Error: Cannot divide by 0!");
}
}
} | 63,120 |
Create a Java class called Employee with a constructor taking name and salary as arguments. | public class Employee
{
private String name;
private double salary;
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
// Getters and setters
public String getName()
{
return name;
}
public void setName(String... | 63,153 |
Fix the syntax error in the following Java code.
String[] x = {"a", "b", "c"}
for (int i=0; i<x.lenght; i++) {
System.out.println(x[i]);
} | String[] x = {"a", "b", "c"};
for (int i=0; i<x.length; i++) {
System.out.println(x[i]);
} | 63,167 |
What is a use case for exception handling in Java? | Exception handling in Java is used to catch and handle errors in code. When an exception occurs, a program may throw an exception object and propagate it to the code that invoked the program; this allows the program to handle the exception and take the necessary actions. Exception handling also allows for code to be wr... | 63,184 |
Create a Java program to print out the number of times a string appears in an array.
array = [“Apple”, “Orange”, “Apple”, “Banana”]
String = “Apple” | public class Main {
public static void main(String[] args) {
String str = "Apple";
String[] array = {"Apple", "Orange", "Apple", "Banana"};
int count = 0;
for(int i=0; i<array.length; i++) {
if(array[i].equals(str)) {
count++;
}
}
... | 63,192 |
Create a hashmap in Java with the following key-value pairs: "Car" -> "Honda", "Flower" -> "Rose". | HashMap<String, String> map = new HashMap<>();
map.put("Car", "Honda");
map.put("Flower", "Rose"); | 63,199 |
Create an array in Java and add the following elements: 5, 7, 3. | int[] arr = {5, 7, 3}; | 63,202 |
Fix the following Java code by adding a missing semicolon.
public static void main(String[] args) {
System.out.println("Hello World") | public static void main(String[] args) {
System.out.println("Hello World");
} | 63,205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.