0% found this document useful (0 votes)
6 views13 pages

Java Programming Solutions and Examples

The document contains a series of Java programming questions and their corresponding solutions, covering various topics such as data structures, algorithms, string manipulation, and concurrency. Each question is followed by a code implementation that demonstrates the solution. The examples include implementing an LRU cache, calculating factorials, and checking for palindromes, among others.

Uploaded by

my.misk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Java Programming Solutions and Examples

The document contains a series of Java programming questions and their corresponding solutions, covering various topics such as data structures, algorithms, string manipulation, and concurrency. Each question is followed by a code implementation that demonstrates the solution. The examples include implementing an LRU cache, calculating factorials, and checking for palindromes, among others.

Uploaded by

my.misk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

21.

Question: Write a program to implement a simple LRU (Least


Recently Used) cache using LinkedHashMap.​
Answer:

import [Link].*;

class LRUCache<K,V> extends LinkedHashMap<K,V> {


private int capacity;
LRUCache(int capacity) {
super(capacity, 0.75f, true);
[Link] = capacity;
}
protected boolean removeEldestEntry([Link]<K,V> eldest) {
return size() > capacity;
}
}

public class Main {


public static void main(String[] args) {
LRUCache<Integer,String> cache = new LRUCache<>(3);
[Link](1,"A"); [Link](2,"B"); [Link](3,"C");
[Link](1); // access 1
[Link](4,"D"); // evicts 2
[Link](cache);
}
}

22. Question: Implement a program to calculate factorial using


recursion and memoization.​
Answer:

import [Link].*;

public class FactorialMemo {


static Map<Integer, Long> memo = new HashMap<>();
static long factorial(int n) {
if(n <= 1) return 1;
if([Link](n)) return [Link](n);
long result = n * factorial(n-1);
[Link](n, result);
return result;
}
public static void main(String[] args) {
[Link](factorial(10));
}
}
23. Question: Write a program to implement a basic ThreadLocal
usage.​
Answer:

public class ThreadLocalDemo {


static ThreadLocal<Integer> threadLocal =
[Link](() -> 0);

public static void main(String[] args) {


Runnable task = () -> {
[Link]((int)([Link]()*100));
[Link]([Link]().getName() +
": " + [Link]());
};
new Thread(task).start();
new Thread(task).start();
}
}

24. Question: Implement a program to sort a map by values.​


Answer:

import [Link].*;
import [Link].*;

public class SortMapByValue {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("Alice", 25); [Link]("Bob", 20);
[Link]("Charlie", 30);

Map<String, Integer> sorted = [Link]()


.stream()

.sorted([Link]())

.collect([Link](
[Link]::getKey,
[Link]::getValue,
(e1,e2)->e1,
LinkedHashMap::new
));
[Link](sorted);
}
}
25. Question: Write a program to count the number of vowels in a
string using streams.​
Answer:

import [Link].*;
import [Link].*;

public class VowelCount {


public static void main(String[] args) {
String str = "Advanced Java Programming";
long count = [Link]()
.mapToObj(c -> (char)c)
.filter(c -> "aeiouAEIOU".indexOf(c) !=
-1)
.count();
[Link](count);
}
}

26. Question: Implement a Java program to remove all null elements


from a list using removeIf().​
Answer:

import [Link].*;

public class RemoveNulls {


public static void main(String[] args) {
List<String> list = new ArrayList<>([Link]("A",
null, "B", null, "C"));
[Link](Objects::isNull);
[Link](list);
}
}

27. Question: Implement a program to find the first non-repeating


character in a string.​
Answer:

import [Link].*;

public class FirstNonRepeatingChar {


public static void main(String[] args) {
String str = "swiss";
Map<Character,Integer> freq = new LinkedHashMap<>();
for(char c : [Link]()) [Link](c,
[Link](c,0)+1);
for([Link]<Character,Integer> e : [Link]()) {
if([Link]() == 1) {
[Link]([Link]()); break; }
}
}
}

28. Question: Write a program to implement a Comparator that


compares strings ignoring case.​
Answer:

import [Link].*;

public class IgnoreCaseSort {


public static void main(String[] args) {
List<String> list = [Link]("Banana", "apple",
"Cherry");
[Link](String.CASE_INSENSITIVE_ORDER);
[Link](list);
}
}

29. Question: Implement a program to check if two strings are


anagrams.​
Answer:

import [Link].*;

public class AnagramCheck {


public static boolean isAnagram(String a, String b) {
char[] arr1 = [Link]().toCharArray();
char[] arr2 = [Link]().toCharArray();
[Link](arr1); [Link](arr2);
return [Link](arr1, arr2);
}
public static void main(String[] args) {
[Link](isAnagram("Listen", "Silent"));
}
}

30. Question: Implement a program to convert a list of integers to


a comma-separated string using streams.​
Answer:

import [Link].*;
import [Link].*;
public class ListToString {
public static void main(String[] args) {
List<Integer> nums = [Link](1,2,3,4,5);
String result =
[Link]().map(String::valueOf).collect([Link](",")
);
[Link](result);
}
}

31. Question: Write a program to implement a basic


producer-consumer problem using wait() and notify().​
Answer:

import [Link].*;

class PC {
private LinkedList<Integer> list = new LinkedList<>();
private int capacity = 5;

public void produce() throws InterruptedException {


int value = 0;
while(true) {
synchronized(this) {
while([Link]() == capacity) wait();
[Link](value++);
[Link]("Produced: " + value);
notify();
[Link](100);
}
}
}

public void consume() throws InterruptedException {


while(true) {
synchronized(this) {
while([Link]()) wait();
int val = [Link]();
[Link]("Consumed: " + val);
notify();
[Link](100);
}
}
}
}

public class ProducerConsumerWaitNotify {


public static void main(String[] args) {
PC pc = new PC();
new Thread(() -> {
try { [Link](); } catch(Exception e) {}
}).start();
new Thread(() -> {
try { [Link](); } catch(Exception e) {}
}).start();
}
}

32. Question: Implement a program to print all prime numbers up to


N using the Sieve of Eratosthenes.​
Answer:

import [Link].*;

public class SievePrimes {


public static void main(String[] args) {
int n = 30;
boolean[] prime = new boolean[n+1];
[Link](prime,true);
prime[0]=prime[1]=false;
for(int i=2;i*i<=n;i++) {
if(prime[i]) {
for(int j=i*i;j<=n;j+=i) prime[j]=false;
}
}
for(int i=2;i<=n;i++) if(prime[i]) [Link](i+"
");
}
}

33. Question: Write a program to find the longest substring without


repeating characters.​
Answer:

import [Link].*;

public class LongestUniqueSubstring {


public static void main(String[] args) {
String str = "abcabcbb";
Set<Character> set = new HashSet<>();
int left=0, max=0;
for(int right=0; right<[Link](); right++) {
while([Link]([Link](right)))
[Link]([Link](left++));
[Link]([Link](right));
max = [Link](max, [Link]());
}
[Link](max);
}
}

34. Question: Implement a program to read a file and print all


lines containing a specific word.​
Answer:

import [Link].*;

public class FindWordInFile {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
String line;
while((line=[Link]())!=null) {
if([Link]("Java")) [Link](line);
}
[Link]();
}
}

35. Question: Write a program to create an immutable class.​


Answer:

final class ImmutableClass {


private final int value;
public ImmutableClass(int value) { [Link]=value; }
public int getValue() { return value; }
}

public class MainImmutable {


public static void main(String[] args) {
ImmutableClass obj = new ImmutableClass(10);
[Link]([Link]());
}
}

36. Question: Implement a program to reverse a string using


StringBuilder.​
Answer:

public class ReverseString {


public static void main(String[] args) {
String str = "Hello World";
String reversed = new
StringBuilder(str).reverse().toString();
[Link](reversed);
}
}

37. Question: Write a program to remove all whitespace from a


string.​
Answer:

public class RemoveWhitespace {


public static void main(String[] args) {
String str = "Java Programming";
str = [Link]("\\s","");
[Link](str);
}
}

38. Question: Implement a Java program to check if a number is a


palindrome.​
Answer:

public class PalindromeNumber {


public static void main(String[] args) {
int num = 12321, original=num, reversed=0;
while(num!=0) {
reversed = reversed*10 + num%10;
num/=10;
}
[Link](original==reversed);
}
}

39. Question: Write a program to implement a simple calculator


using switch statements.​
Answer:

import [Link].*;

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a = 10, b = 5;
char op = '+';
switch(op) {
case '+': [Link](a+b); break;
case '-': [Link](a-b); break;
case '*': [Link](a*b); break;
case '/': [Link](a/b); break;
default: [Link]("Invalid");
}
}
}

40. Question: Implement a program to remove duplicates from a


string.​
Answer:

import [Link].*;

public class RemoveDuplicatesString {


public static void main(String[] args) {
String str = "programming";
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<>();
for(char c : [Link]()) {
if([Link](c)) [Link](c);
}
[Link]([Link]());
}
}

41. Question: Write a program to implement depth-first search (DFS)


in a graph using recursion.​
Answer:

import [Link].*;

public class DFSGraph {


private Map<Integer,List<Integer>> graph = new HashMap<>();
public void addEdge(int u,int v) {
[Link](u,k->new ArrayList<>()).add(v);
}
public void dfs(int start, Set<Integer> visited) {
[Link](start);
[Link](start + " ");
for(int n : [Link](start,new ArrayList<>())) {
if(![Link](n)) dfs(n,visited);
}
}
public static void main(String[] args) {
DFSGraph g = new DFSGraph();
[Link](0,1); [Link](0,2); [Link](1,2);
[Link](2,0); [Link](2,3); [Link](3,3);
[Link](2,new HashSet<>());
}
}

42. Question: Implement a program to calculate the GCD of two


numbers using recursion.​
Answer:

public class GCD {


public static int gcd(int a,int b) {
if(b==0) return a;
return gcd(b,a%b);
}
public static void main(String[] args) {
[Link](gcd(48,18));
}
}

43. Question: Write a program to reverse words in a sentence.​


Answer:

public class ReverseWords {


public static void main(String[] args) {
String sentence = "Java is fun";
String[] words = [Link](" ");
StringBuilder sb = new StringBuilder();
for(int i=[Link]-1;i>=0;i--)
[Link](words[i]).append(" ");
[Link]([Link]().trim());
}
}

44. Question: Implement a program to find duplicate elements in an


array.​
Answer:

import [Link].*;

public class FindDuplicates {


public static void main(String[] args) {
int[] arr = {1,2,3,2,4,1,5};
Set<Integer> set = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for(int n : arr) if(![Link](n)) [Link](n);
[Link](duplicates);
}
}

45. Question: Write a program to implement breadth-first search


(BFS) in a graph.​
Answer:

import [Link].*;

public class BFSGraph {


private Map<Integer,List<Integer>> graph = new HashMap<>();
public void addEdge(int u,int v) {
[Link](u,k->new ArrayList<>()).add(v);
}
public void bfs(int start) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
[Link](start);
[Link](start);
while(![Link]()) {
int node = [Link]();
[Link](node + " ");
for(int n : [Link](node,new
ArrayList<>())) {
if(![Link](n)) {
[Link](n);
[Link](n);
}
}
}
}
public static void main(String[] args) {
BFSGraph g = new BFSGraph();
[Link](0,1); [Link](0,2); [Link](1,2);
[Link](2,0); [Link](2,3); [Link](3,3);
[Link](2);
}
}

46. Question: Implement a program to find the second largest


element in an array.​
Answer:

import [Link].*;

public class SecondLargest {


public static void main(String[] args) {
int[] arr = {10,5,20,8,15};
int first=Integer.MIN_VALUE, second=Integer.MIN_VALUE;
for(int n : arr) {
if(n>first) { second=first; first=n; }
else if(n>second && n!=first) second=n;
}
[Link](second);
}
}

47. Question: Write a program to generate Fibonacci series up to N


terms using recursion.​
Answer:

public class Fibonacci {


public static int fib(int n) {
if(n<=1) return n;
return fib(n-1)+fib(n-2);
}
public static void main(String[] args) {
int N=10;
for(int i=0;i<N;i++) [Link](fib(i)+" ");
}
}

48. Question: Implement a program to merge two HashMaps.​


Answer:

import [Link].*;

public class MergeMaps {


public static void main(String[] args) {
Map<String,Integer> map1 = new HashMap<>();
[Link]("A",1); [Link]("B",2);
Map<String,Integer> map2 = new HashMap<>();
[Link]("B",3); [Link]("C",4);
[Link]((k,v) -> [Link](k,v,Integer::sum));
[Link](map1);
}
}

49. Question: Write a program to implement a priority queue and


poll elements in order.​
Answer:
import [Link].*;

public class PriorityQueueDemo {


public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](5); [Link](1); [Link](3);
while(![Link]()) [Link]([Link]() + " ");
}
}

50. Question: Implement a program to check if a string is a


palindrome ignoring spaces and case.​
Answer:

public class PalindromeString {


public static void main(String[] args) {
String str = "A man a plan a canal Panama";
String cleaned = [Link]("\\s","").toLowerCase();
String reversed = new
StringBuilder(cleaned).reverse().toString();
[Link]([Link](reversed));
}
}

You might also like