0% found this document useful (0 votes)
10 views35 pages

Java Interview Coding Questions With Example

Java Interview Coding Questions with Example Java Interview Coding Questions with Example Java Interview Coding Questions with Example

Uploaded by

Kavitha K
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)
10 views35 pages

Java Interview Coding Questions With Example

Java Interview Coding Questions with Example Java Interview Coding Questions with Example Java Interview Coding Questions with Example

Uploaded by

Kavitha K
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/ 35

[Link]

com/in/kunalkr19

Java Coding Questions with Example

Index
1. Array
2. String
3. Stream API
4. Multithreading
5. Collection Framework
6. Crud Operation using spring boot
7. MySQL

Array

Q. Swap two numbers using temporary variable

Input - a = 10, b = 20;


Output - a = 20 , b = 10

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

Q. Swap two numbers without temporary variable

Input - a = 10, b = 20;


Output - a = 20 , b = 10

public class A {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a + b;
b = a - b;
a = a - b;
[Link](a);
[Link](b);
}
}

Q. Check a number is even or odd

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

Q. Find largest of three numbers

Input - int a = 10;


int b = 15;
int c = 5;
Output - 15

public class A {
public static void main(String[] args) {
int a = 10;
int b = 15;
int c = 5;
int largest = a > (b>c?b:c)?a:(b>c?b:c);
[Link](largest);
}
}

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))){
[Link]("leap year");
}else {
[Link]("not leap year");
}
}
}

Q. Find factorial of a number using for loop

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

Q. Fibonacci Series

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

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

Q. Check a number is prime or not

public class A {
public static void main(String[] args) {
int number = 4;
if (isPrime(number)){
[Link]("number is prime");
}else {
[Link]("number is not prime");
}
}

private static boolean isPrime(int number) {


if (number<=1){
return false;
}
for (int i=2;i<[Link](number);i++){
if (number%i==2){
return false;
}
}
return true;
}
}

Q. Search an element in an array

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


Output - Element is present at index 3

public class A {
public static void main(String[] args) {
int[] arr = {1,2,3,6,8,9,5,0};
int element = 6;
for (int i=0;i<[Link];i++){
if (arr[i]==element){
[Link]("Element is present at index "+i);
break;
}
}
}
}

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};
[Link](arr);
[Link]([Link](arr));
}
}

Q. Find largest element in an array

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

public class A {
public static void main(String[] args) {
int[] arr = {10,324,45,90,9898};
int largest = arr[0];
for (int i=1;i<[Link];i++){
if (arr[i]>largest){
largest = arr[i];
}
}
[Link](largest);
}
}

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<[Link];i++){
if (arr[i]<minimum){
minimum = arr[i];
}
}
[Link](minimum);
}
}

Q. Merge two Arrays

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


int b[] = {45,50,55,60,65};
Output - 30 25 40 45 50 55 60 65

public class A {
public static void main(String[] args) {
int a[] = {30,25,40};
int b[] = {45,50,55,60,65};
int length = [Link] + [Link];
int[] c = new int[length];
for (int i=0;i<[Link];i++){
c[i] = a[i];
}
for (int i =0;i<[Link];i++){
c[[Link]+i] = b[i];
}
for (int x:c){
[Link](x+" ");
}
}
}

String
Q. How to take an input String

public class A{
public static void main(String[] args) {
[Link]("Enter a String :");
Scanner scan = new Scanner([Link]);
String str = [Link]();
[Link](str);
}
}
Q. To get a character from a String

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

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

Input - javaDrogramming
Output - javaProgramming

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

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';
StringBuilder str1 = new StringBuilder(str);
[Link](index,ch);
[Link](str1);
}
}

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


using StringBuffer

Input - javaDrogramming
Output - javaProgramming

public class A {
public static void main(String[] args) {
String str = "javaDrogramming";
int index = 4;
char ch = 'P';
StringBuffer str1 = new StringBuffer(str);
[Link](index,ch);
[Link](str1);
}
}
Q. Reverse a String

Input - ashutosh
Output - hsotuhsa

public class A {
public static void main(String[] args) {
String str = "java";
String revStr = "";
for (int i=0;i<[Link]();i++){
revStr = [Link](i)+revStr;
}
[Link](revStr);
}
}

Q. To sort a String

Input - hello
Output - ehllo

public class A {
public static void main(String[] args) {
String str = "hello";
char[] charArr = [Link]();
[Link](charArr);
String sortedString = new String(charArr);
[Link](sortedString);
}
}
Q. Swapping pair of characters in a String

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

public class A {
public static void main(String[] args) {
String str = "computer";
swapPair(str);
}

private static void swapPair(String str) {


if (str==null||[Link]()){
[Link]("String is null or Empty");
}
char[] ch = [Link]();
for (int i=0;i<[Link]()-1;i=i+2){
char temp = ch[i];
ch[i] = ch[i+1];
ch[i+1] = temp;
}
[Link](ch);
}
}

Q. Find a unicode value of character

public class A {
public static void main(String[] args) {
String str = "abcxyzABCXYZ";
[Link]([Link](0));
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
}
}

Output -
97
98
99
120
121
122

Q. Remove Leading zeros from a String

Input - 0000abc
Output - abc

public class A {
public static void main(String[] args) {
String str = "0000abc";
removeZero(str);
}
private static void removeZero(String str) {
int i=0;
while (i<[Link]()&& [Link](i)=='0') {
i++;
}
StringBuffer sb = new StringBuffer(str);
[Link](0,i,"");
[Link]([Link]());
}
}

Q. Compare to String

public class A {
public static void main(String[] args) {
String str1 = "testing";
String str2 = "testing";
if ([Link](str2)){
[Link]("Both Strings are equals");
}else {
[Link]("String are not equals");
}
}}

Q. Check String is palindrome or not

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

private static boolean checkPalindrome(String str) {

int left = 0;
int right = [Link]()-1;
while (left<right){
if ([Link](left)!=[Link](right)){
return false;
}
left++;
right--;
}
return true;
}
}

Q. Java Program to count occurrence of each


character in a String

Input - ashutosh
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 :[Link]()){
if ([Link](ch)){
[Link](ch,[Link](ch)+1);
}else {
[Link](ch,1);
}
}
[Link](charMapCount);
}
}

Q. Reverse a String using Recursion

Input - ashutosh
Output - hsotuhsa

public class A {
public static void main(String[] args) {
String str = "java";
String revStr = reverseString(str);
[Link](revStr);
}

private static String reverseString(String str) {


if (str==null||[Link]()<=1){
return str;
}
return reverseString([Link](1))+[Link](0);
}
}

Q. Count number of words in a String

Input - java programming questions


Output - 3

public class A {
public static void main(String[] args) {
String str = "java programming questions";
[Link](countWord(str));
}
private static int countWord(String str) {
int wordCount = 1;
for (int i=0;i<[Link]();i++){
if ([Link](i)==' ' && i<[Link]()-1 && [Link](i+1)!='
'){
wordCount++;
}
}
return wordCount;
}
}

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);
}

private static void duplicateCharacter(String str) {


Map<Character,Integer> charMapCount = new
HashMap<>();
for (Character ch:[Link]()){
if ([Link](ch)){
[Link](ch,[Link](ch)+1);
}else {
[Link](ch,1);
}
}
[Link]((key,value)->{
if (value>1){
[Link](key+” “);
}
});
}
}

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<[Link]();i++){
[Link]([Link](i));
}
[Link]("Reverse of String :");
while (![Link]()){
[Link]([Link]());
}
}
}

Q. Find first non-repeating character in a String

Input - java
Output - j,v

public class A {
public static void main(String[] args) {
String str = "java";
Map<Character,Integer> charMapCount = new
HashMap<>();
for (Character ch:[Link]()){
if ([Link](ch)){
[Link](ch,[Link](ch)+1);
}else {
[Link](ch,1);
}
}
for (int i=0;i<[Link]();i++){
char c = [Link](i);
if ([Link](c)==1){
[Link]("first non repeating character "+c);
break;
}
}
}
}

Q. Find the longest common prefix

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


Output - ca

public class A {
public static void main(String[] args) {
String str[] = {"cat", "cable","camera"};
String result = findLongestPrefix(str);
[Link](result);
}

private static String findLongestPrefix(String[] str) {


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

while(j<[Link]()&&j<[Link]()&&[Link]
At(j)==[Link](j)){
j++;
}
if (j==0){
return "";
}
lcp = [Link](0,j);
}
return lcp;
}
}

Q. Check for anagram

Input - String str1 = "car";


String str2 = "rac";
Output - Strings are anagram

public class A {
public static void main(String[] args) {
String str1 = "car";
String str2 = "rac";
if (checkAnagram(str1,str2)){
[Link]("String are anagram");
}else {
[Link]("String are not anagram");
}
}

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


if ([Link]()!=[Link]()){
return false;
}
int[] countArr = new int[26];
for (int i=0;i<[Link]();i++){
countArr[[Link](i)-'a']++;
countArr[[Link](i)-'a']--;
}
for (int i=0;i<[Link];i++){
if (countArr[i]!=0){
return false;
}
}
return true;
}
}

Stream API
Q. Sort a given list in reverse order
Input - [Link](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 = [Link](12, 2,
4, 5, 2, 4, 8);
List<Integer> newList = [Link]().
sorted([Link]()).
collect([Link]());
[Link](newList);

}
}

Q. Given a list of strings, write a Java 8 program to


join the strings with '[' as a prefix, ']' as a suffix, and ','
as a delimiter.

Input - [Link]("adam","mike","sam");
Output - [adam],[mike],[sam]

public class A {
public static void main(String[] args) {
List<String>list=[Link]("adam","mike","sam");
String result = [Link]()
.map(s -> "[" + s + "]")
.collect([Link](","));

[Link](result);

}
}

Q. Find the maximum and minimum of a list of


integers

Input - [Link](1,4,6,8,2);
Output - 8,1

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

List<Integer>list=[Link](1,4,6,8,2);
int max =[Link](list);
int min =[Link](list);
[Link](max);
[Link](min);

}
}

Q. Merge two unsorted arrays into a single sorted


array using Java 8 streams

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


int[] array2 = {7, 2, 8, 4};
Output - [1, 2, 3, 4, 5, 7, 8, 9]

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

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


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

int[] mergeArrya =
[Link]([Link](array1),
[Link](array2))
.sorted().distinct().toArray();
[Link]([Link](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) {

List<Integer>list=[Link](10,50,40,62,4,1,3,5,9);
[Link]().sorted([Link]())
.limit(3).forEach([Link]::println);
[Link]().sorted().
limit(3).forEach([Link]::println);
}
}

[Link] if two strings are anagrams or not using Java


8 streams

public class A {
public static void main(String[] args) {
String s1="listen";
String s2="silent";
String join1 =
[Link]([Link]("")).sorted().collect([Link]
ing(""));
String join2 =
[Link]([Link]("")).sorted().collect([Link]
ing(""));
if([Link](join2)) {
[Link]("anagram");
}else {
[Link]("not anagram");
}
}
}

Q. Sort a list of strings according to the increasing


order of their length
Input - [Link]("BBB","A","CCC","DDDD");
Output - [A, BBB, CCC, DDDD]

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

List<String>list=[Link]("BBB","A","CCC","DDDD");
List<String> list2 = [Link]()

.sorted([Link](String::length))
.collect([Link]());
[Link](list2);
}
}

Q Find the common elements between two arrays


Input - int[]a1= {10,20,30,40};
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 =
[Link](a1).boxed().collect([Link]());
int[] commonElement = [Link](a2).
filter(a->[Link](a)).toArray();
[Link]([Link](commonElement));
}
}

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

Input - [Link]("mike","adam","vikas");
Output - [ekim, mada, sakiv]

A public class A {
public static void main(String[] args) {
List<String>list=[Link]("mike","adam","vikas");
List<StringBuffer> collect = [Link]()
.map(word->new StringBuffer(word).reverse())
.collect([Link]());
[Link]([Link]());
}
}

Q. Find the sum of the first 10 natural numbers


public class A {
public static void main(String[] args) {
int sum = [Link](1, 10).sum();
[Link](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) {
int[] num={15,20,5,60,70,25,30,45,96};
[Link]("original array
"+[Link](num));

int[] reverseArray = [Link](1,


[Link]).map(i -> num[[Link] - i]).toArray();
[Link]("reverse array
"+[Link](reverseArray));

}
}

Q. Print the first 10 even numbers

public class A {
public static void main(String[] args) {
[Link](1,20).filter(i->i%2==0).
forEach([Link]::println);
}
}

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 =
[Link](array).boxed().

collect([Link]([Link](),
[Link]()));

Integer key = [Link]([Link](),


[Link]()).getKey();
[Link](" most repeated element in an
array+"+key);

}
}

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


streams

public class A {
public static void main(String[] args) {
String str="nitin";
String str2="";
for (int i = [Link]()-1; i>=0; i--) {
str2+=[Link](i);
}
if([Link](str)){
[Link]("string is palindrome");
}else{
[Link]("string is not palindrome");
}
}
}

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

Q. Extract duplicate elements from an array

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

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

collect([Link]([Link](),
[Link]()));

[Link]().stream().filter(str->[Link]()>1)
.forEach(entry->
[Link]([Link]()+[Link]()));

}
}

Q. Find the first repeated character in a string

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

String str = "banana";


Map<Character, Long> charCountMap = [Link]()
.mapToObj(c -> (char)
c).collect([Link](c -> c, LinkedHashMap::new,
[Link]()));
Character c = [Link]()
.stream().filter(entry -> [Link]() >
1)

.map([Link]::getKey).findFirst().orElseThrow(() -> new


IllegalArgumentException("No non-repeated character found in
the string."));
[Link](c);

}
}

[Link] the first non-repeated character in a string

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

String str = "banana";


Map<Character, Long> charCountMap = [Link]()
.mapToObj(c -> (char)
c).collect([Link](c -> c, LinkedHashMap::new,
[Link]()));
Character c = [Link]()
.stream().filter(entry -> [Link]() ==
1)

.map([Link]::getKey).findFirst().orElseThrow(() -> new


IllegalArgumentException("No non-repeated character found in
the string."));
[Link](c);

}
}

[Link] the first 10 odd numbers

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

[Link](1, 20).filter(i -> i % 2 != 0)


.forEach([Link]::println);
}
}

Q Write a Java 8 program to get the last element of an


array.

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

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

int[] num = {15, 2, 65, 85, 74, 36, 74, 52, 25, 36,
74, 85};
[Link]("Original array: " +
[Link](num));
int lastElement = [Link](num)
.reduce((first, second) -> second)
.orElseThrow(() -> new IllegalArgumentException("Array is
empty"));
[Link]("Last element: " + lastElement);
}
}

Q. Write a program to append char in char

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

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

Stream<Character> charStream = [Link]('A', 'B',


'C');
[Link](ch -> {
char newChar = (char) (ch + 23);
[Link](ch + "_" + newChar);
});
}
}

[Link] to find duplicate elements in a given integers


list in java using Stream functions?
public class A {
public static void main(String[] args) {

List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
[Link]()
.filter(n -> ![Link](n))
.forEach([Link]::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,
r=3, s=1, t=5, u=1}

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

// Join the list into a single string


String combinedString = [Link]().
collect([Link]());
Map<String, Long> collect =
[Link]([Link](" ", "").split(""))

.collect([Link](String::toLowerCase,
[Link]()));
[Link](collect);

}
}

[Link]

You might also like