# Java Programs
## Q. Write a function to find out duplicate words in a given string?
**Approach:**
1. Define a string.
1. Convert the string into lowercase to make the comparison insensitive.
1. Split the string into words.
1. Two loops will be used to find duplicate words. Outer loop will select a word and Initialize variable count to 1. Inner loop will compare the word selected by outer loop with rest of the words.
1. If a match found, then increment the count by 1 and set the duplicates of word to '0' to avoid counting it again.
1. After the inner loop, if count of a word is greater than 1 which signifies that the word has duplicates in the string.
```java
public class DuplicateWord {
public static void main(String[] args) {
String string = "Big black bug bit a big black dog on his big black nose";
int count;
//Converts the string into lowercase
string = string.toLowerCase();
//Split the string into words using built-in function
String words[] = string.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
//Set words[j] to 0 to avoid printing visited word
words[j] = "0";
}
}
//Displays the duplicate word if count is greater than 1
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
```
Output
```java
Duplicate words in a given string :
big
black
```
## Q. Find the missing number in an array?
**Approach:**
1. Calculate `A = n (n+1)/2` where n is largest number in series 1…N.
1. Calculate B = Sum of all numbers in given series
1. Missing number = A – B
```java
// Java program to find missing Number
public class Test {
public static void main(String[] args) {
int total;
int[] numbers = new int[]{1, 2, 3, 4, 6, 7};
total = 7;
int expected_sum = total * ((total + 1) / 2);
int num_sum = 0;
for (int i: numbers) {
num_sum += i;
}
System.out.print( expected_sum - num_sum );
}
}
```
Output
```
5
```
## Q. Write a program to generate random numbers between the given range?
**Approach**
1. Get the Min and Max which are the specified range.
1. Call the nextInt() method of ThreadLocalRandom class (java.util.concurrent.ThreadLocalRandom) and specify the Min and Max value as the parameter as
`ThreadLocalRandom.current().nextInt(min, max + 1);`
1. Return the received random value
```java
// Java program to generate a random integer
// within this specific range
import java.util.concurrent.ThreadLocalRandom;
class GFG {
public static int getRandomValue(int Min, int Max)
{
// Get and return the random integer
// within Min and Max
return ThreadLocalRandom
.current()
.nextInt(Min, Max + 1);
}
// Driver code
public static void main(String[] args)
{
int Min = 1, Max = 100;
System.out.println("Random value between "
+ Min + " and " + Max + ": "
+ getRandomValue(Min, Max));
}
}
```
**Input**
```
Input: Min = 1, Max = 10
```
**Output**
```
Random value between 1 and 100: 35
```
## Q. Write a java program to swap two string variables without using temp variable?
**Approach**
1. Append second string to first string and store in first string:
a = a + b
2. call the method substring(int beginindex, int endindex)
by passing beginindex as 0 and endindex as,
a.length() - b.length():
b = substring(0,a.length()-b.length());
3. call the method substring(int beginindex) by passing
b.length() as argument to store the value of initial
b string in a
a = substring(b.length());
```java
/**
* Java program to swap two strings without using a temporary
* variable.
**/
import java.util.*;
class Swap
{
public static void main(String args[]) {
// Declare two strings
String a = "Hello";
String b = "World";
// Print String before swapping
System.out.println("Strings before swap: a = " + a + " and b = "+b);
// append 2nd string to 1st
a = a + b;
// store intial string a in string b
b = a.substring(0, a.length() - b.length());
// store initial string b in string a
a = a.substring(b.length());
// print String after swapping
System.out.println("Strings after swap: a = " + a + " and b = " + b);
}
}
```
Output
```
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello
```
## Q. Write a java program to Move all zeroes to end of array?
```
Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output: arr[] = {1, 2, 4, 3, 5, 0, 0, 0};
```
```java
public class Test
{
static void pushZerosToEnd(int arr[], int n) {
int count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is
// non-zero, then replace the element at index 'count'
// with this element
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}
public static void main (String[] args) {
int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9};
int n = arr.length;
pushZerosToEnd(arr, n);
System.out.println("Array after pushing zeros to the back: ");
for (int i=0; i LongestSub
```
## Q. A Program to check if strings are rotations of each other or not?
**Approach**
1. Create a temp string and store concatenation of str1 to str1 in temp.
temp = str1.str1
2. If str2 is a substring of temp then str1 and str2 are rotations of each other.
Example:
str1 = "ABACD"
str2 = "CDABA"
temp = str1.str1 = "ABACDABACD"
Since str2 is a substring of temp, str1 and str2 are rotations of each other.
```java
class StringRotation
{
static boolean areRotations(String str1, String str2) {
// There lengths must be same and str2 must be
// a substring of str1 concatenated with str1.
return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1);
}
public static void main (String[] args) {
String str1 = "AACD";
String str2 = "ACDA";
if (areRotations(str1, str2))
System.out.println("Strings are rotations of each other");
else
System.out.printf("Strings are not rotations of each other");
}
}
```
Output
```
Strings are rotations of each other
```
## Q. Can you write a regular expression to check if String is a number?
```java
public class StringTest
{
public static void main (String[] args) {
String regex = "[0-9]+";
// String regex = "\\d+";
String data = "23343453";
System.out.println("Is Number: "+ data.matches(regex));
}
}
```
Output
```
Is Number: true
```
## Q. Write a program to find top two maximum numbers in a array?
```java
public class TwoMaxNumbers {
public void printTwoMaxNumbers(int[] nums) {
int maxOne = 0;
int maxTwo = 0;
for(int n:nums) {
if(maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if(maxTwo < n) {
maxTwo = n;
}
}
System.out.println("First Max Number: "+maxOne);
System.out.println("Second Max Number: "+maxTwo);
}
public static void main(String a[]) {
int num[] = {5,34,78,2,45,1,99,23};
TwoMaxNumbers tmn = new TwoMaxNumbers();
tmn.printTwoMaxNumbers(num);
}
}
```
Output
```
First Max Number: 99
Second Max Number: 78
```
## Q. How to find all the leaders in an integer array in java?
An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
```java
public class Test
{
void printLeaders(int arr[], int size) {
for (int i = 0; i < size; i++) {
int j;
for (j = i + 1; j < size; j++) {
if (arr[i] lhs.weight - rhs.weight);
minHeap.add(new Node(source, 0));
// set infinite distance from source to v initially
List dist = new ArrayList(Collections.nCopies(N, Integer.MAX_VALUE));
// distance from source to itself is zero
dist.set(source, 0);
// boolean array to track vertices for which minimum
// cost is already found
boolean[] done = new boolean[N];
done[0] = true;
// stores predecessor of a vertex (to print path)
int prev[] = new int[N];
prev[0] = -1;
// run till minHeap is not empty
while (!minHeap.isEmpty()) {
// Remove and return best vertex
Node node = minHeap.poll();
// get vertex number
int u = node.vertex;
// do for each neighbor v of u
for (Edge edge: graph.adjList.get(u)) {
int v = edge.dest;
int weight = edge.weight;
// Relaxation step
if (!done[v] && (dist.get(u) + weight) < dist.get(v)) {
dist.set(v, dist.get(u) + weight);
prev[v] = u;
minHeap.add(new Node(v, dist.get(v)));
}
}
// marked vertex u as done so it will not get picked up again
done[u] = true;
}
for (int i = 1; i < N; ++i) {
System.out.print("Path from vertex 0 to vertex " + i + " has minimum cost of "
+ dist.get(i) + " and the route is [ ");
printRoute(prev, i);
System.out.println("]");
}
}
public static void main(String[] args) {
// initialize edges as per above diagram
// (u, v, w) triplet represent undirected edge from
// vertex u to vertex v having weight w
List edges = Arrays.asList(
new Edge(0, 1, 10), new Edge(0, 4, 3),
new Edge(1, 2, 2), new Edge(1, 4, 4),
new Edge(2, 3, 9), new Edge(3, 2, 7),
new Edge(4, 1, 1), new Edge(4, 2, 8),
new Edge(4, 3, 2)
);
// Set number of vertices in the graph
final int N = 5;
// construct graph
Graph graph = new Graph(edges, N);
shortestPath(graph, 0, N);
}
}
```
Output
```
Path from vertex 0 to vertex 1 has minimum cost of 4 and the route is [ 0 4 1 ]
Path from vertex 0 to vertex 2 has minimum cost of 6 and the route is [ 0 4 1 2 ]
Path from vertex 0 to vertex 3 has minimum cost of 5 and the route is [ 0 4 3 ]
Path from vertex 0 to vertex 4 has minimum cost of 3 and the route is [ 0 4 ]
```
## Q. How to display 10 random numbers using forEach()?
```java
( new Random ())
.ints ()
.limit ( 10 )
.forEach ( System . out :: println);
```
## Q. How can I display unique squares of numbers using the method map()?
```java
Stream
.of ( 1 , 2 , 3 , 2 , 1 )
.map (s -> s * s)
.distinct ()
.collect ( Collectors . toList ())
.forEach ( System . out :: println);
```
## Q. How to display the number of empty lines using the method filter()?
```java
System.out.println (
Stream
.of ( " Hello " , " " , " , " , " world " , " ! " )
.filter ( String :: isEmpty)
.count ());
```
## Q. How to display 10 random numbers in ascending order?
```java
( new Random ())
.ints ()
.limit ( 10 )
.sorted ()
.forEach ( System . out :: println);
```
## Q. How to find the maximum number in a set?
```java
Stream
.of ( 5 , 3 , 4 , 55 , 2 )
.mapToInt (a -> a)
.max ()
.getAsInt (); // 55
```
## Q. How to find the minimum number in a set?
```java
Stream
.of ( 5 , 3 , 4 , 55 , 2 )
.mapToInt (a -> a)
.min ()
.getAsInt (); // 2
```
## Q. How to get the sum of all numbers in a set?
```java
Stream
.of( 5 , 3 , 4 , 55 , 2 )
.mapToInt()
.sum(); // 69
```
## Q. How to get the average of all numbers?
```java
Stream
.of ( 5 , 3 , 4 , 55 , 2 )
.mapToInt (a -> a)
.average ()
.getAsDouble (); // 13.8
```
## Q. How to get current date using Date Time API from Java 8?
```java
LocalDate as.now();
```
## Q. How to add 1 week, 1 month, 1 year, 10 years to the current date using the Date Time API?
```java
LocalDate as.now ().plusWeeks ( 1 );
LocalDate as.now ().plusMonths ( 1 );
LocalDate as.now ().plusYears ( 1 );
LocalDate as.now ().plus ( 1 , ChronoUnit.DECADES );
```
## Q. How to get the next Tuesday using the Date Time API?
```java
LocalDate as.now().with( TemporalAdjusters.next ( DayOfWeek.TUESDAY ));
```
## Q. How to get the current time accurate to milliseconds using the Date Time API?
```java
new Date ().toInstant ();
```
## Q. How to get the second Saturday of the current month using the Date Time API?
```java
LocalDate
.of ( LocalDate.Now ().GetYear (), LocalDate.Now ().GetMonth (), 1 )
.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SATURDAY ))
.with ( TemporalAdjusters.next ( DayOfWeek.SATURDAY ));
```
## Q. How to get the current time in local time accurate to milliseconds using the Date Time API?
```java
LocalDateTime.ofInstant ( new Date().toInstant(), ZoneId.systemDefault());
```
## Q. How to sort a list of strings using a lambda expression?
```java
public static List < String > sort ( List < String > list) {
Collections.sort(list, (a, b) -> a.compareTo(b));
return list;
}
```
#### Q. How to find if there is a sub array with sum equal to zero?
#### Q. How to remove a given element from array in Java?
#### Q. How to find trigonometric values of an angle in java?
#### Q. Reverse and add until you get a palindrome
#### Q. Selection sort in java
#### Q. Write a singleton class in java?
#### Q. How to calculate complexity of algorithm?
#### Q. Implement Producer Consumer design Pattern in Java using wait, notify and notifyAll method in Java?
#### Q. Find Minimum numbers of platforms required for railway station in java
#### Q. How to check whether given number is binary or not?
#### Q. Armstrong number program in java
#### Q. How to find sum of all digits of a number in java?
#### Q. How to find largest number less than a given number and without a given digit?
#### Q. Roman equivalent of a decimal number
#### Q. How to check whether user input is number or not in java?
#### Q. Write a program to convert decimal number to binary format.
#### Q. Write a program to find perfect number or not.
#### Q. Write a program to find sum of each digit in the given number using recursion.
#### Q. Write a program to check the given number is a prime number or not?
#### Q. Write a program to check the given number is binary number or not?
#### Q. Find prime factors of number in java
#### Q. Write code to avoid deadlock in Java where N threads are accessing N shared resources?
#### Q. How to sort an array in place using QuickSort algorithm?
#### Q. Write a program to find intersection of two sorted arrays in Java?
#### Q. How find the first repeating element in an array of integers?
#### Q. How to find first non-repeating element in array of integers?
#### Q. How to find top two numbers from an integer array?
#### Q. How to find the smallest positive integer value that cannot be represented as sum of any subset of a given array?
#### Q. How to merge sorted array?
#### Q. How to find sub array with maximum sum in an array of positive and negative number?
#### Q. How to find sub array with largest product in array of both positive and negative number?
#### Q. Write a program to find length of longest consecutive sequence in array of integers?
#### Q. How to find minimum value in a rotated sorted array?
#### Q. Given an array of of size n and a number k, find all elements that appear more than n/k times?
#### Q. Returns the largest sum of contiguous integers in the array
#### Q. Return the sum two largest integers in an array
#### Q. How to search an array to check if an element exists there?
#### Q. How to copy array in Java?
#### Q. Write a function to find out longest palindrome in a given string?
#### Q. Can you make array volatile in Java?
#### Q. How to find top two numbers from an integer array in Java?
#### Q. Can you pass the negative number as an array size?
#### Q. What is an anonymous array? Give example?
#### Q. What is the difference between int[] a and int a[] ?
#### Q. What are jagged arrays in java? Give example?
#### Q. While creating the multidimensional arrays, can you specify an array dimension after an empty dimension?
#### Q. How to reverse Singly Linked List?
#### Q. Create a Java program to find middle node of linked list in Java in one pass?
#### Q. How to find if a linked list contains cycle or not in Java?
#### Q. How to find nth element from end of linked list
#### Q. How to check if linked list is palindrome in java
#### Q. Add two numbers represented by linked list in java
#### Q. How to sort a Stack using a temporary Stack?
#### Q. Implement Binary Search Tree (BST)
#### Q. Find min and max value from Binary Search Tree (BST)
#### Q. Find height of a Binary Search Tree (BST)
#### Q. Implement Binary Search Tree (BST) Level order traversal (breadth first).
#### Q. Implement Binary Search Tree (BST) pre-order traversal (depth first).
#### Q. Implement Binary Search Tree (BST) in-order traversal (depth first).
#### Q. Implement Binary Search Tree (BST) post-order traversal (depth first).
#### Q. How to check the given Binary Tree is Binary Search Tree (BST) or not?
#### Q. How to delete a node from Binary Search Tree (BST)?
#### Q. Binary tree level order traversal
#### Q. Binary tree spiral order traversal
#### Q. Binary tree reverse level order traversal
#### Q. Binary tree boundary traversal
#### Q. Print leaf nodes of binary tree
#### Q. Count leaf nodes in binary tree
#### Q. Get maximum element in binary tree
#### Q. Print all paths from root to leaf in binary tree
#### Q. Print vertical sum of binary tree in java
#### Q. Get level of node in binary tree in java
#### Q. Lowest common ancestor(LCA) in binary tree in java
#### Q. Search element in row wise and column wise sorted matrix
#### Q. Stock buy and sell to maximize profit.
#### Q. How to implement merge sort in java
#### Q. How to implement bubble sort in java
#### Q. How to implement insertion sort in java
#### Q. Write a program to implement hashcode and equals.
#### Q. Write wait-notify code for producer-consumer problem?
#### Q. Write a program to implement ArrayList.
#### Q. A maximal subarray
#### Q. Sort a linked list
#### Q. Iterative Quick sort
#### Q. Bucket sort
#### Q. Counting sort
#### Q. Square root of number
#### Q. Printing patterns
#### Q. Leap year
#### Q. Design a Vending Machine
#### Q. Transpose a matrix
#### Q. Adding two matrices in Java
#### Q. Matrix multiplication
#### Q. Write a java program to print Floyd’s Triangle?
#### Q. Spiral Matrix Program.
#### Q. Anagram program in java
#### Q. Write a program to print fibonacci series.
#### Q. How to you calculate the difference between two dates in Java?
#### Q. Java Program to find gcd and lcm of two numbers
#### Q. Write a program to find the sum of the first 1000 prime numbers?
#### Q. How to perform matrix operations in java?