Category: Java programming question
-
Write a Java program to demonstrate deadlock
Deadlock is a situation when two or more threads are indefinitely blocked waiting for each other. In below example, there are two threads, Thread1 and Thread2. Two resources are represented by two strings, resource1 and resource2. Thread1 first gets a lock on resource1 and then resource2. Thread2 first gets a lock on resource2 and then…
-
Remove white spaces from String in Java
Remove white spaces from string using build-in methods Approach: We’ll use replaceAll() method of String class and replace all white spaces with “”. Output Note: We could have used “\s+” instead of “\s”. Both produce the same result with almost same performance. But, when the number of consecutive spaces increase, “\s+” is faster than “\s”.…
-
Write Java program to print Fibonacci series
Fibonacci series is a series of numbers in which each number(Fibonnaci number) is the sum of the two preceding numbers, starting from 0 and 1. For example:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 There are two ways to generate Fibonacci series in Java: Fibonacci series without recursion Output Fibonacci series using…
-
How to remove duplicates from ArrayList?
The task is to remove duplicate elements from the ArrayList. For Example: Approach 1 – Using Iterator Approach 2 – LinkedHashSet We have used LinkedHashSet because it maintains insertion order. Approach 3 You can use Java 8 Streams to remove duplicate elements from a list by using the distinct() method.
-
Java Program to find second largest number in Array
Approach 1 Sort the array in descending order and then return the second element from the array. The time complexity of this solution is O(nlogn). This solution has problem if first two numbers in sorted array are equal. Approach 2 Second and a better solution is to traverse the array twice. In first traversal find…
-
Java program to reverse a string without String class’s reverse() function.
We’ll use the following approach in this example: Output
-
Java Program to swap two numbers without using a third variable(method 1).
This approach uses addition and subtraction to swap two numbers. The logic to solve this problem is to first assign one of the two numbers with the sum of two numbers. Since, this number will now have the sum of two numbers, assign second number the difference of first number(which is now the sum of…
