instruction
stringlengths
25
5.05k
output
stringlengths
4
8.53k
__index_level_0__
int64
34
78.2k
Create a web server in Java to handle a POST request.
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class WebServer { public static void main(String[] args) throws Exception { // listen for a connection from a client ServerSocket connection = ne...
68,488
Output the result of 2 to the power of 8 in Java.
int result = (int) Math.pow(2, 8); System.out.println(result); //Output: 256
68,489
Implement a webhook endpoint in Java using Spring MVC to process a payment request.
@RestController public class PaymentController { @PostMapping("/payment") public void processPayment(@RequestBody PaymentRequest request) { // Process the payment inside this method } }
68,499
Rewrite the following Java code using a switch statement instead of if/else. int time = 10; if (time < 12) { System.out.println("Good morning"); } else if (time < 17) { System.out.println("Good afternoon"); } else { System.out.println("Good evening"); }
int time = 10; switch (time) { case time < 12: System.out.println("Good morning"); break; case time < 17: System.out.println("Good afternoon"); break; case time >= 17: System.out.println("Good evening"); break; }
68,520
Design a method for reversing a string in Java
public static String reverse(String str) { String reversedString = ""; for (int i = str.length() - 1; i >= 0; i--) { reversedString += str.charAt(i); } return reversedString; }
68,536
Construct an if-else statement to determine if a given number is divisible by 4
if (number % 4 == 0) System.out.println("The number is divisible by 4"); else System.out.println("The number is not divisible by 4");
68,544
Edit the following code in Java to include a new method “printName()”. public class Person { String name; void displayAge(){ System.out.println("age is: "+ age); } }
public class Person { String name; void displayAge(){ System.out.println("age is: "+ age); } void printName(){ System.out.println("Name: "+ name); } }
68,553
Write a Java program to calculate the area of a square given the length of a side.
public class CalculateSquareArea { public static double calculateArea(double sideLength) { double area = sideLength * sideLength; return area; } public static void main(String[] args) { double sideLength = 5; double area = calculateArea(sideLength); System.out.println("The area of a squa...
68,582
How can you remove duplicate characters from a string in Java?
We can use a Set collection to remove duplicate characters from a string in Java. We can loop through the characters in the string, and add them to a Set, which does not allow duplicate elements. Then we can loop through the set and append each character to a new string. This new string will be free of duplicate charac...
68,594
Create a Java method that computes the factorial of an integer.
public static int factorial(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; }
68,595
Create a class in Java that will print the two integers added together.
public class Addition { public static int add(int x, int y) { return x + y; } public static void main(String[] args) { System.out.println(add(5,7)); } }
68,605
What changes can you suggest in order to optimize the following Java code? public class Student { //private variables private String name; private int age; private int grade;
public class Student { //private variables private String name; private int age; private int grade; //create getters and setters for the fields public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge()...
68,607
Create a while loop in Java to calculate the Fibonacci numbers up to the number 10.
int num1 = 0, num2 = 1, fibo = 0; while(fibo <= 10) { fibo = num1 + num2; num1 = num2; num2 = fibo; System.out.print(fibo +" "); }
68,623
Create a list of 5 strings in Java.
List<String> list = Arrays.asList("hello", "world", "news", "sun", "moon");
68,656
Modify the given Java code to print the first character of each word in a sentence. String sentence = "Today is a good day";
String sentence = "Today is a good day"; String[] words = sentence.split(" "); for (String word : words) { System.out.print(word.charAt(0)); }
68,664
What is the syntax of an if-else block in Java?
The syntax of an if-else block in Java is: if (condition) { // execute this code if the condition is true } else { // execute this code if the condition is false }
68,666
Which of the following statements is/are valid in Javascript? let x = "Hello World!"; let y = 'Hello World!'
Both statements are valid in Javascript. The first statement uses double quotes, while the second statement uses single quotes.
68,711
Identify the correct syntax to declare a variable in Java
dataType variableName;
68,725
Output a triangle shape using only asterisks (e.g. *) in Java.
public class Triangle { public static void main(String[] args) { int limit=15; System.out.println("Right Angle Triangle"); for (int i = 0; i < limit; i++) { for (int j = 0; j <= i; j++) { System.out.print("*"); } ...
68,736
Output all items from an array in descending order in Java.
public static void printDescendingOrder(int[] arr) { // sort the array in descending order Arrays.sort(arr, Collections.reverseOrder()); for (int i=0; i<arr.length; i++) System.out.print(arr[i] + " "); }
68,739
Write a Java code snippet to set the 3rd element in an array of integers to the value 5. int[] arr = {1, 2, 3, 4, 5};
arr[2] = 5;
68,755
Generate a unique 8 digit alphanumeric ID using Java.
String alphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz"; StringBuilder sb = new StringBuilder(8); for (int i = 0; i < 8; i++) { int index = (int)(alphaNumericString.length() * Math.random()); sb.append(alphaNumericString....
68,759
Generate a class in Java for a contact record, including name, age, phone number, email, and address information.
public class Contact { String name; int age; String phoneNumber; String email; String address; public Contact(String name, int age, String phoneNumber, String email, String address){ this.name = name; this.age = age; this.phoneNumber = phoneNumber; t...
68,762
Write a method 'addString' in Java that takes two strings as parameters and returns a single string that concatenates the two strings.
public static String addString(String str1, String str2) { return str1 + str2; }
68,795
Provide instructions to create a linked list in Java.
In Java, to create a linked list, you need to declare a node class with instance variables for data and reference to the next node. Then create a LinkedList class with a head node and other methods for insertion, deletion and searching in the linked list. To add an element to the linked list, create a node with the giv...
68,801
Develop a GUI application in Java to reverse a string. User should be able to enter a string in the text field.
import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; class Reverse extends JFrame { JTextField inputTF; JTextField outputTF; JButton reverseBtn; Reverse() { inputTF = new JTextField(20);...
68,864
Create an algorithm in Java that prints the prime numbers between 1 and 100.
class PrimeNumber{ public static void main(String args[]){ int i,m=0,flag=0; int n=100;//it is the number to be checked m=n/2; for(i=2;i<=m;i++){ if(n%i==0){ System.out.println("Number is not prime"); flag=1; break; } } if(flag==0) System.out.p...
68,870
Given a course consisting of 5 lessons, write a program to display the first lesson. Lessons = ["Python Basics", "Javascript Basics", "C++ Basics", "Data Structures", "Object-Oriented Programming"]
def display_first_lesson(lessons): print("The first lesson is: " + lessons[0]) Lessons = ["Python Basics", "Javascript Basics", "C++ Basics", "Data Structures", "Object-Oriented Programming"] display_first_lesson(Lessons)
68,887
Show the memory size of a list using Java. List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(4); list.add(5);
// Show the memory size of the list int memorySize = list.size() * Integer.SIZE / 8; System.out.println(memorySize);
68,894
Create an ArrayList in Java
The syntax to create an ArrayList in Java would be: ArrayList<dataType> listName = new ArrayList<dataType>(); Replace dataType with the appropriate type of data that needs to be stored in the list and listName with the desired name of the list.
68,935
Rewrite the given code so that it uses Java 8 features. import java.util.ArrayList; List<String> list = new ArrayList<String>(); int sum = 0; for(String str: list){ sum += Integer.parseInt(str); }
import java.util.List; List<String> list = List.of("1","2","3","4"); int sum = list.stream() .mapToInt(Integer::parseInt) .sum();
68,950
Create a basic log in security system in Java
boolean checkLogin(String username, String password) { boolean success = false; if(username.equals("admin") && password.equals("admin")) { success = true; } return success; }
68,974
Create a Java program which will print the following pattern.
public class Pattern { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); } System.out.println(); } } } // Output 1 22 333 4444 55555
68,995
Write a Java program that takes a String as parameter and counts how many words are in it.
public class WordCounter { public static int countWords(String s) { String trimStr = s.trim(); if (trimStr.isEmpty()) return 0; return trimStr.split("\\s+").length; } public static void main(String args[]) { String s = "This is a sample sentence"; System...
69,003
Create a Java program to list all duplicated words in the given string. He explained the problem in an intelligent and articulate manner.
import java.util.LinkedHashSet; public class DuplicateWords { public static void findDuplicates(String str) { String[] words = str.split("\\s+"); LinkedHashSet<String> set = new LinkedHashSet<>(); for (int i = 0; i < words.length; i++) { if (!set.add(words[i])) { ...
69,028
Create a Java program which takes a year as input and prints whether it is a leap year or not. year = 2020
public class LeapYear { public static void main(String args[]) { int year = 2020; if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) System.out.println("The year is a leap year."); else System.out.println("The year is not a leap year."); }...
69,080
Suggest a one-line solution for intersecting two given arrays in Javascript.
const intersection = (arr1, arr2) => arr1.filter(x => arr2.includes(x));
69,089
Create a class in Java called Student which contains string 'name' and int 'grade'.
public class Student { private String name; private int grade; public void setName(String name) { this.name = name; } public void setGrade(int grade) { this.grade = grade; } public String getName() { return name; } public int getGrade() { return grade; } }
69,113
Define a Java class 'Fruits' with three instance variables - name(String), quantity(int), and colour(String).
public class Fruits { String name; int quantity; String colour; public Fruits(String name, int quantity, String colour) { this.name = name; this.quantity = quantity; this.colour = colour; } }
69,141
Complete the program written in Java to add two numbers and print out the sum. int a = 3; int b = 5;
public class AddNumbers { public static void main(String[] args) { int a = 3; int b = 5; int sum = a + b; System.out.println("Sum is: " + sum); } }
69,146
Design a data structure in Java for storing student information.
public class Student { private String studentId; private String name; private int age; private String school; private String address; private String phoneNumber; //Getters and Setters public String getStudentId() { return studentId; } public void setStudentId(Strin...
69,149
Create a class in Java for representing a Rectangle that stores length and width attributes and a method to calculate its area.
public class Rectangle { int length; int width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public int calculateArea() { return this.length * this.width; } }
69,189
Write a Java code snippet for creating an array with 10 random numbers between 1 and 50.
int[] randNums = new int[10]; Random rand = new Random(); for(int i = 0; i < randNums.length; i++) { randNums[i] = rand.nextInt(50) + 1; }
69,191
Write a java code to take a string as input and return the number of words present in it.
import java.util.StringTokenizer; public class WordCounter { public static int countWords(String str) { StringTokenizer tokenizer = new StringTokenizer(str); return tokenizer.countTokens(); } public static void main(String[] args) { String str = "Geeks for Geeks...
69,198
Write a loop in Java to add all elements of a given array. int[] arr = {1, 2, 3, 4, 5};
int sum = 0; for (int i = 0; i < arr.length; i++) sum += arr[i];
69,237
Write a Java class to define a student object that includes a name and a grade.
public class Student { //instance variables String name; int grade; //constructor public Student(String studentName, int studentGrade) { name = studentName; grade = studentGrade; } //methods public String getName(){ return name;...
69,337
Write an Iterative program in Java to print the first n terms of the Fibonacci sequence.
public static void printFibonacciIterative(int n) { int prev1=0, prev2=1, sum=0; for (int i = 0; i < n; i++) { System.out.print(sum + " "); prev2 = sum; sum = prev1 + prev2; prev1 = prev2; } }
69,338
Convert the string "Hello World" to upper case using a Java program.
String upperCaseString = "Hello World".toUpperCase();
69,355
Print all the numbers in a given string using Java. String str = "123XYZ456ABC789"
for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { System.out.print(str.charAt(i) + " "); } } // Output -> 1 2 3 4 5 6 7 8 9
69,358
Create a program in Java to print a multiplication table of size 5x5.
for (int i = 1; i <= 5; i++) { System.out.printf("%d * %d = %d\n", i, i, i * i); for (int j = 1; j <= 5; j++) { System.out.printf("%d * %d = %d\n", i, j, i * j); } System.out.println(); }
69,359
What is the syntax for creating an object of the "Car" class in Java?
The syntax for creating an object of the "Car" class in Java is: Car myCar = new Car();
69,362
Implement a comparator method in Java to compare two objects of the same class. class Country { String name; double population; double area; }
class CountryComparator implements Comparator<Country> { @Override public int compare(Country c1, Country c2) { //compare by population if (c1.population < c2.population) { return -1; } else if (c1.population > c2.population) { return 1; } else { ...
69,376
Compile and execute this Java code. public class Main { public static void main(String[] args) { System.out.println("Welcome to Java"); } }
Compilation successful. Welcome to Java
69,383
Write a Java program to insert a new node into a singly linked list. head -> 3 -> 4 -> 6 -> null
// Insert 8 after 4 public static Node insertNode(Node head, int data) { Node node = new Node(data); // Empty List if (head == null) { node.next=null; head = node; return head; } Node CurrNode = head; while (CurrNode.data != 4) { Cur...
69,403
Write a Java program to remove comments from the Java program. public class HelloWorld { /* This is a multiline comment. */ public static void main(String[] args) { System.out.println("Hello World!"); // This is a single line comment. } }
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
69,425
Use Java to generate a string containing 1000 random characters of length 10.
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder randomString = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < 1000; i++){ int randIndex = rand.nextInt(chars.length()); randomString.append(chars.charAt(randIndex)); } String result = randomString.toString();
69,450
Debug the following Java program to get the output "Can you try again? public class TryAgain { public static void main (String[] args) { x = 4; System.out.println(x = 4); } }
public class TryAgain { public static void main (String[] args) { int x = 4; System.out.println("Can you try again?"); } }
69,456
Generate a correct Java program to swap two given numbers.
public class Swap { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("before swap: a = "+a+" b = "+b); int temp = a; a = b; b = temp; System.out.println("after swap: a = "+a+" b = "+b); } }
69,462
Edit the following code so that it prints out a right triangle of size n int n = 5; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { System.out.print("*"); } System.out.println(); }
int n = 5; for (int i = n; i > 0; i--) { for(int j = 0; j < i; j++) { System.out.print("*"); } System.out.println(); }
69,463
Write a Java program that prints all numbers between 1 to 100.
public class PrintNumbers{ public static void main(String[] args){ // Prints numbers from 1 to 100 for(int i = 1; i <= 100; i++){ System.out.println(i); } } }
69,488
Generate a Java program that prints the sum of digits of a given number. 17
public class SumOfDigits { public static void main(String args[]) { int num = 17; int sum = 0; while(num > 0) { sum += num % 10; num /= 10; } System.out.println("Sum of Digits of the Number: " +sum); } }
69,496
Describe the different types of loops in Java.
In Java, there are three types of loops: while loops, for loops and do-while loops. While loops execute a block of code until a certain condition is met. For loops are used when the number of iterations is known, with the loop iterating a specific number of times. Do-while loops are similar to while loops, except the c...
69,497
Design a Java program to display the given integer in reverse. 6789
public class ReverseNumber { public static void main(String[] args) { int num = 6789; int reversed = 0; while(num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println("Rev...
69,498
Create a Java program that print the Fibonacci sequence in the given range. min = 0, max = 10
public class Fibonacci { public static void main(String[] args) { int min = 0, max = 10; int prev = 0, next = 1; System.out.print("Fibonacci Sequence in the given range:"); for (int i = 0; i <= max; i++) { if (i >= min) { System.out.print(" " + prev); ...
69,525
Generate the for loop in Java for iterating from 0 to the given number. 4
for (int i = 0; i < 4; i++) { //code to be executed }
69,528
Edit the following code so that it prints the given value to the console. System.out.println("Hello World"); 5
System.out.println(5);
69,529
Modify the following code so that it prints out the characters from the given string one at a time. String str = "Hello World";
String str = "Hello World"; for (int i = 0; i < str.length(); i++) { System.out.println(str.charAt(i)); }
69,534
Design a Java class for a Car which has the following attributes: name, model, year, and price.
class Car { private String name; private String model; private int year; private double price; //constructor to initialize Car object public Car(String name, String model, int year, double price) { this.name = name; this.model = model; this.year = year; this.price = price; } //getters and setters...
69,594
Design a data structure in Java to store and sort a list of customers by their age.
public class Customer{ private int age; private String name; public Customer(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } } public class AgeSortedCustomerList {...
69,603
What does the “static” keyword do in Java?
The "static" keyword in Java is used to define static members of a class. This includes static methods, static variables, static blocks, and static inner classes. Static methods can be invoked without creating an instance of the class, and static variables are shared among all objects of the same class.
69,626
Create a Java class named "MyClass" with three methods - getName(), setName(), and displayName().
public class MyClass { private String name; // constructor public MyClass(String name) { this.name = name; } // getName public String getName() { return this.name; } // setName public void setName(String name) { this.name = name; } // displayName public void...
69,641
Develop a Java code which assigns each element of an array to an individual variable.
int[] myArray = {1,2,3}; int first = myArray[0]; int second = myArray[1]; int third = myArray[2];
69,664
Write a Java program to read in a list of integers and separate them into two lists of even and odd numbers. [1, 4, 6, 7, 8, 10, 12]
List even = [4, 6, 8, 10, 12] List odd = [1, 7]
69,666
Use an object oriented approach to create an object in Java to store the temperature, humidity and wind speed from a weather forecast.
class WeatherData { private int temperature; private int humidity; private int windSpeed; // ... setter and getter methods }
69,667
Use an object oriented approach to create a class in Java to store the cost and name of an item.
class Item { private String name; private double cost; // ... setter and getter methods }
69,670
Rewrite the following instruction to print the binary value it holds. int n = 12;
System.out.println(Integer.toBinaryString(n));
69,684
Write a Java method to remove all whitespaces from a string
public static String removeWhitespace(String str) { return str.replaceAll("\\s", ""); }
69,685
Write a Java program to get the day of the month from given a Date object
public class DayFromDate { public static void main(String[] args) { Date date = new Date(); System.out.println("Day of the month: " + date.getDate()); } }
69,688
Implement a method in Java to generate a random float within the given range. min = 0.3 max = 0.7
/** * Generates a random float value within the given range (inclusive). * @param min the minimum value of the range * @param max the maximum value of the range * @return a random float value within the range */ public static float randomFloat(float min, float max) { Random rand = new Random(); return rand...
69,711
Create a Java program to find a number in an array and print its index. int[] arr = {1, 2, 3, 4, 5}; int num = 3;
public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int num = 3; int index = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] == num) { index = i; break; } } if (index == -1) { S...
69,737
Create a Java program to print all natural numbers between 1 and 50, both inclusive.
public class Natural { public static void main(String[] args) { int n = 1; while (n <= 50) { System.out.println(n); n = n + 1; } } }
69,757
How do the following Java methods work? public static void main(String[] args) { int[] arr = {2,4,6,8,10}; int n = 2; int result = binarySearch(arr, 0, arr.length-1, n); if (result == -1) System.out.println("Element is not present"); else System.out.println("Element is present...
The main method takes an array of integers and an element to search for. It calls binarySearch method which uses the binary search algorithm to search for the element in the given array. The algorithm starts by calculating the mid point of the given array. If the element at the mid point is equal to the element to sear...
69,767
What will be printed with the following Java code? String myString = "Hello World"; for (int i = 0; i < myString.length(); i++) { System.out.print(i + " = " + myString.charAt(i) + " "); }
0 = H 1 = e 2 = l 3 = l 4 = o 5 = 6 = W 7 = o 8 = r 9 = l 10 = d
69,770
Create a dictionary in Java containing employee information with their names as the key and salary as the values.
Map<String, Integer> employeeMap = new HashMap<>(); employeeMap.put("John", 1000); employeeMap.put("Amy", 1200); employeeMap.put("Dad", 1500); employeeMap.put("Mom", 2000);
69,777
Suggest a way to persistently store data in a Java program.
A convenient way to persistently store data in a Java program is to use a database such as MySQL or SQLite. You can also use an API to store data in the cloud, such as AWS S3. Additionally, many Java libraries provide support for persistence such as JPA and Hibernate, which provide object-relational mapping and object-...
69,783
Explain the purpose of the keyword ``this`` in Java.
In Java, the keyword "this" is used to refer to the current object. It can be used to access the values of instance variables and to call methods within the current object. It can also be used to pass the object itself as an argument to another method. "this" is used to differentiate instance variables from local varia...
69,784
Write a Java program to read in a string and print its length.
import java.util.Scanner; public class StringLength { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputString = scanner.nextLine(); System.out.println("Length of the string is: "+ inputString.length()); } }
69,800
In Java, write a program to read in an array of 5 integers and output their sum. [2, 5, 9, 8, 6]
import java.util.Scanner; public class ArraySum { public static void main(String[] args) { int[] array = {2, 5, 9, 8, 6}; int sum = 0; for (int i = 0; i < array.length; i++) { sum = sum + array[i]; } System.out.println("The sum of the array is: "+sum); } }
69,801
Create a class in Java that assigns a value to a given variable. String variable = "Hello world"
public class VariableAssignment { private String variable; public VariableAssignment(String variable) { this.variable = variable; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } }
69,838
Write a method in Java for checking if a String is a palindrome.
public static boolean isPalindrome(String str) { int n = str.length(); for (int i = 0; i < n/2; i++){ if (str.charAt(i) != str.charAt(n-i-1)) return false; } return true; }
69,843
Design a solution using Java to calculate the mean of all the numbers in a given array. [4, 7, 11, 15, 18, 21]
public static double mean(int[] array) { double sum = 0; int length = array.length; // loop through each number and calculate the sum for (int num : array) sum += num; // calculate the mean and return it return sum/ length; }
69,858
Code a method in Java to print out the elements of a 2D array. [[1,2,3], [4,5,6], [7,8,9]]
public class TwoDArray{ public static void print2DArray(int[][] arr){ for (int[] row : arr){ for (int element : row){ System.out.print(element+" "); } System.out.println(); } } public static void main(String[] args) { int[][] a...
69,866
Code a method in Java to sort an array. [2, 9, 4, 6, 5, 1]
public class SortExample{ public static void insertionSort(int[] arr){ int n = arr.length; for (int i=1; i<n; i++){ int key = arr[i]; int j = i - 1; while ( j>=0 && arr[j] > key){ arr[j+1] = arr[j]; j--; } ar...
69,867
Create a Java method to print all elements in an array in reverse order.
public static void printReverse(int[] array) { for (int i = array.length - 1; i >= 0; i--) { System.out.println(array[i]); } }
69,874
Design a Java program to find the maximum of 3 numbers. 1, 2, 5
public class Maximum { public static int getMax(int num1, int num2, int num3) { int max = num1; if (num2 > max) { max = num2; } if (num3 > max) { max = num3; } return max; } public static void main(String[] args) { int max = getMax(1,2,5); System.out.println("Maxim...
69,900
Design a Data Structure in Javascript to store a list of tasks.
class TaskList { constructor() { this.tasks = [] } add_task(task) { this.tasks.push(task); } remove_task(task) { const i = this.tasks.indexOf(task); if (i !== -1) { this.tasks.splice(i, 1); } } count_tasks() { return this.tasks.length; } }
69,902
Using variable A, write a code snippet in Java to iterate through ArrayList and delete odd values. // ArrayList A ArrayList<Integer> A = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
for(int i=0; i<A.size(); i++) { if(A.get(i) %2 != 0) { A.remove(i); i--; } }
69,964
Implement a LRU cache in Java
import java.util.HashMap; public class LRUCache { // Custom Doubly Linked List static class CacheNode { CacheNode prev; CacheNode next; int key; int value; } // Map containing the Keys private HashMap<Integer, CacheNode> map = new HashMap<Int...
70,026
Create a Java program to print out Armstrong numbers in a given range.
public static void armstrongInRange(int lower, int upper) { int num, originalNum, remainder, n = 0; // Calculates the number of digits a number has for(originalNum = lower + 1; originalNum < upper; originalNum++) { num = originalNum; while(num != 0) { num /...
70,051
Implement an algorithm in Java to count the number of ones in a binary number
public static int countOnes(int num) { int count = 0; while (num != 0) { num = num & (num - 1); count++; } return count; }
70,082