0% found this document useful (0 votes)
6 views

Coding Questions

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 views

Coding Questions

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
You are on page 1/ 37

Created By -

Ashutosh
phone - 8960972274
LinkedIn - Loading…
Git & GitHub - Loading…
Instagram - Loading…

sh
Topmate.io - Loading…

to
Click on link or scan QR for Whatsapp Group -

hu
https://chat.whatsapp.com/Iy2Ag6hE35WENehlmNcctV
As
ith
W
de
co
Index
1. Array
2. String
3. Stream API
4. Multithreading

sh
5. Collection Framework
6. Crud Operation using spring boot

to
7. MySQL

hu
As
Array
ith
W

Q. Swap two numbers using temporary variable


de

Input - a = 10, b = 20;


Output - a = 20 , b = 10
co

public class A {
public static void main(String[] args) {
int a = 10;
int b = 20;
int temp = a;
a = b;
b = temp;
System.out.println(a);
System.out.println(b);
}
}

sh
Q. Swap two numbers without temporary variable

to
Input - a = 10, b = 20;
Output - a = 20 , b = 10

hu
public class A {
public static void main(String[] args) {
As
int a = 10;
int b = 20;
a = a + b;
ith

b = a - b;
a = a - b;
W

System.out.println(a);
System.out.println(b);
de

}
}
co

Q. Check a number is even or odd

public class A {
public static void main(String[] args) {
int number = 15;
if (number%2==0){
System.out.println("number is even");
}else {
System.out.println("number is odd");
}
}
}

sh
Q. Find largest of three numbers

to
Input - int a = 10;

hu
int b = 15;
int c = 5;
Output - 15
As
public class A {
public static void main(String[] args) {
ith

int a = 10;
int b = 15;
W

int c = 5;
int largest = a > (b>c?b:c)?a:(b>c?b:c);
de

System.out.println(largest);
}
}
co

Q. Check a year is leap year or not

public class A {
public static void main(String[] args) {
int year = 2020;
if ((year%4==0)||((year%4==0)&&(year%100!=0))){
System.out.println("leap year");
}else {
System.out.println("not leap year");
}
}
}

sh
Q. Find factorial of a number using for loop

to
public class A {

hu
public static void main(String[] args) {
int number = 5;
int fact = 1;
As
for (int i=2;i<=5;i++){
fact = fact*i;
}
ith

System.out.println(fact);
}
W

}
de

Q. Fibonacci Series

0, 1, 1, 2, 3, 5, 8, 13, 21, 34
co

public class A {
public static void main(String[] args) {
int n1 = 0;
int n2 = 1;
int count = 10;
System.out.print(n1+" "+n2);
for (int i=2;i<count;i++){
int n3 = n1 + n2;
System.out.print(" "+n3);
n1 = n2;
n2 = n3;
}

sh
}
}

to
Q. Check a number is prime or not

hu
public class A {
public static void main(String[] args) {
As
int number = 4;
if (isPrime(number)){
System.out.println("number is prime");
ith

}else {
System.out.println("number is not prime");
W

}
}
de

private static boolean isPrime(int number) {


if (number<=1){
co

return false;
}
for (int i=2;i<Math.sqrt(number);i++){
if (number%i==2){
return false;
}
}
return true;
}
}

Q. Search an element in an array

sh
Input - int[] arr = {1,2,3,6,8,9,5,0};

to
Output - Element is present at index 3

hu
public class A {
public static void main(String[] args) {
int[] arr = {1,2,3,6,8,9,5,0};
As
int element = 6;
for (int i=0;i<arr.length;i++){
if (arr[i]==element){
ith

System.out.println("Element is present at index "+i);


break;
W

}
}
de

}
}
co

Q. Sort an Array

Input - {3,4,6,7,3,6,2};
Output - [2, 3, 3, 4, 6, 6, 7]

public class A {
public static void main(String[] args) {
int [] arr = {3,4,6,7,3,6,2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}

sh
Q. Find largest element in an array

to
Input - {10,324,45,90,9898};
Output - 9898

hu
public class A {
public static void main(String[] args) {
As
int[] arr = {10,324,45,90,9898};
int largest = arr[0];
for (int i=1;i<arr.length;i++){
ith

if (arr[i]>largest){
largest = arr[i];
W

}
}
de

System.out.println(largest);
}
}
co

Q. Find minimum element in an array

Input - {10,324,45,90,9898};
Output - 10
public class A {
public static void main(String[] args) {
int[] arr = {10,324,45,90,9898};
int minimum = arr[0];
for (int i=1;i<arr.length;i++){
if (arr[i]<minimum){
minimum = arr[i];

sh
}
}

to
System.out.println(minimum);
}

hu
}

Q. Merge two Arrays


As
input - int a[] = {30,25,40};
ith

int b[] = {45,50,55,60,65};


Output - 30 25 40 45 50 55 60 65
W

public class A {
public static void main(String[] args) {
de

int a[] = {30,25,40};


int b[] = {45,50,55,60,65};
int length = a.length + b.length;
co

int[] c = new int[length];


for (int i=0;i<a.length;i++){
c[i] = a[i];
}
for (int i =0;i<b.length;i++){
c[a.length+i] = b[i];
}
for (int x:c){
System.out.print(x+" ");
}
}
}

sh
to
hu
As
String
ith
W

Q. How to take an input String


de

public class A{
public static void main(String[] args) {
co

System.out.println("Enter a String :");


Scanner scan = new Scanner(System.in);
String str = scan.next();
System.out.println(str);
}
}
Q. To get a character from a String

public class A {
public static void main(String[] args) {
String str = "javaProgramming";
int index = 4;

sh
System.out.println(str.charAt(index));
}

to
}

hu
Q. Replace a character at a specific index in a String

Input - javaDrogramming
As
Output - javaProgramming
ith

public class A {
public static void main(String[] args) {
String str = "javaDrogramming";
W

int index = 4;
char ch = 'P';
de

str = str.substring(0,index) + ch + str.substring(index+1);


System.out.println(str);
}
co

Q. Replace a character at a specific index in a String


using StringBuilder

Input - javaDrogramming
Output - javaProgramming

public class A {
public static void main(String[] args) {
String str = "javaDrogramming";
int index = 4;
char ch = 'P';

sh
StringBuilder str1 = new StringBuilder(str);
str1.setCharAt(index,ch);

to
System.out.println(str1);
}

hu
}

Q. Replace a character at a specific index in a String


As
using StringBuffer
ith

Input - javaDrogramming
Output - javaProgramming
W

public class A {
public static void main(String[] args) {
de

String str = "javaDrogramming";


int index = 4;
char ch = 'P';
co

StringBuffer str1 = new StringBuffer(str);


str1.setCharAt(index,ch);
System.out.println(str1);
}
}
Q. Reverse a String

Input - ashutosh
Output - hsotuhsa

public class A {
public static void main(String[] args) {

sh
String str = "java";
String revStr = "";

to
for (int i=0;i<str.length();i++){
revStr = str.charAt(i)+revStr;

hu
}
System.out.println(revStr);
}
As
}

Q. To sort a String
ith

Input - hello
W

Output - ehllo
de

public class A {
public static void main(String[] args) {
String str = "hello";
co

char[] charArr = str.toCharArray();


Arrays.sort(charArr);
String sortedString = new String(charArr);
System.out.println(sortedString);
}
}
Q. Swapping pair of characters in a String

Input - computer
Output - [o, c, p, m, t, u, r, e]

public class A {

sh
public static void main(String[] args) {
String str = "computer";

to
swapPair(str);
}

hu
private static void swapPair(String str) {
if (str==null||str.isEmpty()){
As
System.out.println("String is null or Empty");
}
char[] ch = str.toCharArray();
ith

for (int i=0;i<str.length()-1;i=i+2){


char temp = ch[i];
W

ch[i] = ch[i+1];
ch[i+1] = temp;
de

}
System.out.println(ch);
}
co

Q. Find a unicode value of character

public class A {
public static void main(String[] args) {
String str = "abcxyzABCXYZ";
System.out.println(str.codePointAt(0));
System.out.println(str.codePointAt(1));
System.out.println(str.codePointAt(2));
System.out.println(str.codePointAt(3));
System.out.println(str.codePointAt(4));
System.out.println(str.codePointAt(5));

sh
}
}

to
Output -

hu
97
98
99
As
120
121
122
ith

Q. Remove Leading zeros from a String


W

Input - 0000abc
de

Output - abc

public class A {
co

public static void main(String[] args) {


String str = "0000abc";
removeZero(str);
}
private static void removeZero(String str) {
int i=0;
while (i<str.length()&& str.charAt(i)=='0') {
i++;
}
StringBuffer sb = new StringBuffer(str);
sb.replace(0,i,"");
System.out.println(sb.toString());
}

sh
}

to
Q. Compare to String

hu
public class A {
public static void main(String[] args) {
String str1 = "testing";
As
String str2 = "testing";
if (str1.equals(str2)){
System.out.println("Both Strings are equals");
ith

}else {
System.out.println("String are not equals");
W

}
}}
de

Q. Check String is palindrome or not


co

public class A {
public static void main(String[] args) {
String str = "madam";
if (checkPalindrome(str)){
System.out.println("String is palindrome");
}else {
System.out.println("String is not palindorme");
}
}

private static boolean checkPalindrome(String str) {

sh
int left = 0;
int right = str.length()-1;

to
while (left<right){
if (str.charAt(left)!=str.charAt(right)){

hu
return false;
}
left++;
As
right--;
}
return true;
ith

}
}
W

Q. Java Program to count occurrence of each


de

character in a String

Input - ashutosh
co

Output - {a=1, s=2, t=1, u=1, h=2, o=1}

public class A {
public static void main(String[] args) {
String str = "ashutosh";
Map<Character, Integer> charMapCount = new
HashMap<>();
for (Character ch :str.toCharArray()){
if (charMapCount.containsKey(ch)){
charMapCount.put(ch,charMapCount.get(ch)+1);
}else {
charMapCount.put(ch,1);

sh
}
}

to
System.out.println(charMapCount);
}

hu
} As
Q. Reverse a String using Recursion

Input - ashutosh
ith

Output - hsotuhsa
W

public class A {
public static void main(String[] args) {
de

String str = "java";


String revStr = reverseString(str);
System.out.println(revStr);
co

private static String reverseString(String str) {


if (str==null||str.length()<=1){
return str;
}
return reverseString(str.substring(1))+str.charAt(0);
}
}

Q. Count number of words in a String

Input - java programming questions

sh
Output - 3

to
public class A {
public static void main(String[] args) {

hu
String str = "java programming questions";
System.out.println(countWord(str));
}
As
private static int countWord(String str) {
int wordCount = 1;
for (int i=0;i<str.length();i++){
ith

if (str.charAt(i)==' ' && i<str.length()-1 && str.charAt(i+1)!='


'){
W

wordCount++;
}
de

}
return wordCount;
}
co

Q. Find Duplicate character in a String

Input - programming
Output - r g m
public class A {
public static void main(String[] args) {
String str = "programming";
duplicateCharacter(str);
}

sh
private static void duplicateCharacter(String str) {
Map<Character,Integer> charMapCount = new

to
HashMap<>();
for (Character ch:str.toCharArray()){

hu
if (charMapCount.containsKey(ch)){
charMapCount.put(ch,charMapCount.get(ch)+1);
}else {
As
charMapCount.put(ch,1);
}
}
ith

charMapCount.forEach((key,value)->{
if (value>1){
W

System.out.print(key+” “);
}
de

});
}
}
co

Q. Reverse a String using stack

Input - ashutosh
Output - hsotuhsa
public class A {
public static void main(String[] args) {
String str = "java";
Stack<Character> stack = new Stack<>();
for (int i=0;i<str.length();i++){
stack.push(str.charAt(i));
}

sh
System.out.println("Reverse of String :");
while (!stack.empty()){

to
System.out.print(stack.pop());
}

hu
}
}
As
Q. Find first non-repeating character in a String

Input - java
ith

Output - j,v
W

public class A {
public static void main(String[] args) {
de

String str = "java";


Map<Character,Integer> charMapCount = new
HashMap<>();
co

for (Character ch:str.toCharArray()){


if (charMapCount.containsKey(ch)){
charMapCount.put(ch,charMapCount.get(ch)+1);
}else {
charMapCount.put(ch,1);
}
}
for (int i=0;i<str.length();i++){
char c = str.charAt(i);
if (charMapCount.get(c)==1){
System.out.println("first non repeating character "+c);
break;
}

sh
}
}

to
}

hu
Q. Find the longest common prefix

Input - {"cat", "cable","camera"}


As
Output - ca

public class A {
ith

public static void main(String[] args) {


String str[] = {"cat", "cable","camera"};
W

String result = findLongestPrefix(str);


System.out.println(result);
de

private static String findLongestPrefix(String[] str) {


co

if (str==null||str.length==0){
return "";
}
String lcp = str[0];
for (int i=1;i<str.length;i++){
String currentWord = str[i];
int j=0;

while(j<currentWord.length()&&j<lcp.length()&&currentWord.char
At(j)==lcp.charAt(j)){
j++;
}
if (j==0){

sh
return "";
}

to
lcp = currentWord.substring(0,j);
}

hu
return lcp;
}
}
As
Q. Check for anagram
ith

Input - String str1 = "car";


String str2 = "rac";
W

Output - Strings are anagram


de

public class A {
public static void main(String[] args) {
String str1 = "car";
co

String str2 = "rac";


if (checkAnagram(str1,str2)){
System.out.println("String are anagram");
}else {
System.out.println("String are not anagram");
}
}

private static boolean checkAnagram(String str1, String str2) {


if (str1.length()!=str2.length()){
return false;
}
int[] countArr = new int[26];

sh
for (int i=0;i<str1.length();i++){
countArr[str1.charAt(i)-'a']++;

to
countArr[str2.charAt(i)-'a']--;
}

hu
for (int i=0;i<countArr.length;i++){
if (countArr[i]!=0){
return false;
As
}
}
return true;
ith

}
}
W

Stream API
de
co

Q. Sort a given list in reverse order


Input - Arrays.asList(12, 2, 4, 5, 2, 4, 8);
Output - [12, 8, 5, 4, 4, 2, 2]

public class A {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(12, 2,
4, 5, 2, 4, 8);
List<Integer> newList = list.stream().
sorted(Comparator.reverseOrder()).
collect(Collectors.toList());
System.out.println(newList);

sh
}

to
Q. Given a list of strings, write a Java 8 program to
join the strings with '[' as a prefix, ']' as a suffix, and ','

hu
as a delimiter.
As
Input - Arrays.asList("adam","mike","sam");
Output - [adam],[mike],[sam]
ith

public class A {
public static void main(String[] args) {
List<String>list=Arrays.asList("adam","mike","sam");
W

String result = list.stream()


.map(s -> "[" + s + "]")
.collect(Collectors.joining(","));
de

System.out.println(result);
co

}
}

Q. Find the maximum and minimum of a list of


integers

Input - Arrays.asList(1,4,6,8,2);
Output - 8,1

public class A {
public static void main(String[] args) {

List<Integer>list=Arrays.asList(1,4,6,8,2);
int max =Collections.max(list);
int min =Collections.min(list);
System.out.println(max);

sh
System.out.println(min);

to
}

hu
Q. Merge two unsorted arrays into a single sorted
array using Java 8 streams
As
Input - int[] array1 = {5, 3, 9, 1};
int[] array2 = {7, 2, 8, 4};
ith

Output - [1, 2, 3, 4, 5, 7, 8, 9]
W

public class A {
public static void main(String[] args) {
de

int[] array1 = {5, 3, 9, 1};


int[] array2 = {7, 2, 8, 4};
co

int[] mergeArrya =
IntStream.concat(Arrays.stream(array1),
Arrays.stream(array2))
.sorted().distinct().toArray();
System.out.println(Arrays.toString(mergeArrya));
}
}
Q. Get the three maximum and three minimum
numbers from a given list of integers

public class A {
public static void main(String[] args) {

sh
List<Integer>list=Arrays.asList(10,50,40,62,4,1,3,5,9);
list.stream().sorted(Comparator.reverseOrder())

to
.limit(3).forEach(System.out::println);
list.stream().sorted().
limit(3).forEach(System.out::println);

hu
}
}
As
Q.check if two strings are anagrams or not using Java
8 streams
ith

public class A {
W

public static void main(String[] args) {


String s1="listen";
String s2="silent";
de

String join1 =
Arrays.stream(s1.split("")).sorted().collect(Collectors.join
ing(""));
co

String join2 =
Arrays.stream(s2.split("")).sorted().collect(Collectors.join
ing(""));
if(join1.equals(join2)) {
System.out.println("anagram");
}else {
System.out.println("not anagram");
}
}
}

Q. Sort a list of strings according to the increasing


order of their length

sh
Input - Arrays.asList("BBB","A","CCC","DDDD");
Output - [A, BBB, CCC, DDDD]

to
public class A {
public static void main(String[] args) {

hu
List<String>list=Arrays.asList("BBB","A","CCC","DDDD");
List<String> list2 = list.stream()
As
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
ith

System.out.println(list2);
}
}
W
de

Q Find the common elements between two arrays


Input - int[]a1= {10,20,30,40};
co

int[]a2= {40,30,50};
Output - [40, 30]

public class A {
public static void main(String[] args) {
int[]a1= {10,20,30,40};
int[]a2= {40,30,50};
Set<Integer> set =
Arrays.stream(a1).boxed().collect(Collectors.toSet());
int[] commonElement = Arrays.stream(a2).
filter(a->set.contains(a)).toArray();
System.out.println(Arrays.toString(commonElement));
}
}

sh
Q. Reverse each word of a string using Java 8 streams

to
Input - Arrays.asList("mike","adam","vikas");
Output - [ekim, mada, sakiv]

hu
A public class A {
public static void main(String[] args) {
List<String>list=Arrays.asList("mike","adam","vikas");
As
List<StringBuffer> collect = list.stream()
.map(word->new StringBuffer(word).reverse())
.collect(Collectors.toList());
ith

System.out.println(collect.toString());
}
}
W

Q. Find the sum of the first 10 natural numbers


de

public class A {
public static void main(String[] args) {
co

int sum = IntStream.rangeClosed(1, 10).sum();


System.out.println(sum);

}
}
Q. Reverse an integer array

Input - {15,20,5,60,70,25,30,45,96};
Output - reverse array [96, 45, 30, 25, 70, 60, 5, 20, 15]

public class A {
public static void main(String[] args) {

sh
int[] num={15,20,5,60,70,25,30,45,96};
System.out.println("original array
"+Arrays.toString(num));

to
int[] reverseArray = IntStream.rangeClosed(1,
num.length).map(i -> num[num.length - i]).toArray();

hu
System.out.println("reverse array
"+Arrays.toString(reverseArray));
As
}
}
ith

Q. Print the first 10 even numbers


W

public class A {
de

public static void main(String[] args) {


IntStream.rangeClosed(1,20).filter(i->i%2==0).
forEach(System.out::println);
co

}
}

Q. Find the most repeated element in an array


Input - {1,2,3,4,5,6,3,4,6,7,3,5};
Output - 3

public class A {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6,3,4,6,7,3,5};
Map<Integer, Long> collect =
Arrays.stream(array).boxed().

collect(Collectors.groupingBy(Function.identity(),

sh
Collectors.counting()));

Integer key = Collections.max(collect.entrySet(),

to
Map.Entry.comparingByValue()).getKey();
System.out.println(" most repeated element in an

hu
array+"+key);

}
}
As
ith

Q. Check if a string is a palindrome using Java 8


streams
W

public class A {
public static void main(String[] args) {
de

String str="nitin";
String str2="";
for (int i = str.length()-1; i>=0; i--) {
co

str2+=str.charAt(i);
}
if(str2.equals(str)){
System.out.println("string is palindrome");
}else{
System.out.println("string is not palindrome");
}
}
}

**************************************************************

Q. Extract duplicate elements from an array

sh
public class A {
public static void main(String[] args) {

to
int []num={5,25,10,36,25,45,65,75,45,85,95,5};
Map<Integer, Long> collect =

hu
Arrays.stream(num).boxed().

collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
As
collect.entrySet().stream().filter(str->str.getValue()>1)
ith

.forEach(entry->
System.out.println(entry.getKey()+entry.getValue()));
W

}
}
de

Q. Find the first repeated character in a string


co

public class A {
public static void main(String[] args) {

String str = "banana";


Map<Character, Long> charCountMap = str.chars()
.mapToObj(c -> (char)
c).collect(Collectors.groupingBy(c -> c, LinkedHashMap::new,
Collectors.counting()));
Character c = charCountMap.entrySet()
.stream().filter(entry -> entry.getValue() >
1)

.map(Map.Entry::getKey).findFirst().orElseThrow(() -> new


IllegalArgumentException("No non-repeated character found in

sh
the string."));
System.out.println(c);

to
}
}

hu
Q.Find the first non-repeated character in a string
As
public class A {
ith

public static void main(String[] args) {

String str = "banana";


W

Map<Character, Long> charCountMap = str.chars()


.mapToObj(c -> (char)
c).collect(Collectors.groupingBy(c -> c, LinkedHashMap::new,
de

Collectors.counting()));
Character c = charCountMap.entrySet()
.stream().filter(entry -> entry.getValue() ==
co

1)

.map(Map.Entry::getKey).findFirst().orElseThrow(() -> new


IllegalArgumentException("No non-repeated character found in
the string."));
System.out.println(c);

}
}

Q.Print the first 10 odd numbers

public class A {
public static void main(String[] args) {

sh
IntStream.rangeClosed(1, 20).filter(i -> i % 2 != 0)
.forEach(System.out::println);

to
}
}

hu
Q Write a Java 8 program to get the last element of an
As
array.
ith

Original array: [15, 2, 65, 85, 74, 36, 74, 52, 25, 36, 74, 85]
Last element: 85
W

public class A {
public static void main(String[] args) {
de

int[] num = {15, 2, 65, 85, 74, 36, 74, 52, 25, 36,
74, 85};
co

System.out.println("Original array: " +


Arrays.toString(num));
int lastElement = Arrays.stream(num)
.reduce((first, second) -> second)
.orElseThrow(() -> new IllegalArgumentException("Array is
empty"));
System.out.println("Last element: " + lastElement);
}
}

Q. Write a program to append char in char

input- {A, B, C}
output->[A_X, B_Y, C_Z]

sh
public class A {
public static void main(String[] args) {

to
Stream<Character> charStream = Stream.of('A', 'B',

hu
'C');
charStream.forEach(ch -> {
char newChar = (char) (ch + 23);
System.out.println(ch + "_" + newChar);
As
});
}
}
ith

Q.How to find duplicate elements in a given integers


W

list in java using Stream functions?


de

public class A {
public static void main(String[] args) {
co

List<Integer> myList =
Arrays.asList(10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
myList.stream()
.filter(n -> !set.add(n))
.forEach(System.out::println);
}
}
Write a program to print the count of each character
in a String? and remove white space

Input - string data to count each character


Output - {a=5, c=4, d=1, e=2, g=1, h=2, i=1, n=2, o=2,

sh
r=3, s=1, t=5, u=1}

public class A {

to
public static void main(String[] args) {
List<String> list = Arrays.asList("string data to
count each character");

hu
// Join the list into a single string
String combinedString = list.stream().
As
collect(Collectors.joining());
Map<String, Long> collect =
Stream.of(combinedString.replace(" ", "").split(""))
ith

.collect(Collectors.groupingBy(String::toLowerCase,
Collectors.counting()));
W

System.out.println(collect);

}
de

}
co
co
de
W
ith
As
hu
to
sh

You might also like