Monday, May 20, 2019

Can you write an algorithm to print the following pattern?

Problem statement:
Given an input string from the console as follows

Sample I/O:

aaaaa, bbbb, cccc, d , f , g , i
Sample O/P:
a5, b4, c4,d1, f1, h1, g1, i1
  1. import java.util.Scanner;
  2. public class SwitchStatement {
  3.     public static void main(String[] args) {
  4.         Scanner sc = new Scanner(System.in);
  5.         System.out.println("Enter the pattern.");
  6.         String pattern = sc.nextLine();
  7.         System.out.println(pattern.charAt(0) + "" + pattern.length());
  8.     }
  9. }

Sunday, May 19, 2019

How do you sort an array based on count of occurrences in descending order


How do you sort an array based on count of occurrences in ascending order

Problem statement:
Given an array of integer, you have to sort based on count of occurrences in ascending order?
  1. import java.util.*;
  2. public class SortArrayInDesc {
  3.     public static void main(String[] args) {
  4.         int a[] = {2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 1, 1, 1};
  5.         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  6.         for (int i = 0; i < a.length; i++) {
  7.             if (map.containsKey(a[i])) {
  8.               map.put(a[i], map.get(a[i]) + 1);
  9.             } else {
  10.                 map.put(a[i], 1);
  11.             }
  12.         }
  13.         ValueComparator<Integer, Integer> comparator = new ValueComparator<Integer, Integer>(map);
  14.         TreeMap<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(comparator);
  15.         sortedMap.putAll(map);
  16.         ArrayList<Integer> lists = new ArrayList<Integer>();
  17.         for (Integer i : sortedMap.keySet()) {
  18.             for (int c = 0; c < sortedMap.get(i); c++) {
  19.                 lists.add(i);
  20.             }
  21.         }
  22.         System.out.println(lists.toString());
  23.     }
  24. }
  1. import java.util.Comparator;
  2. import java.util.Map;
  3. public class ValueComparator<T1, T2 extends Comparable<T2>> implements Comparator<T1> {
  4.     Map<T1, T2> map;
  5.     public ValueComparator(Map<T1, T2> map) {
  6.         this.map = map;
  7.     }
  8.     @Override
  9.     public int compare(T1 k1, T1 k2) {
  10.         T2 val1 = map.get(k1);
  11.         T2 val2 = map.get(k2);

  12.         return val1.compareTo(val2);
  13.     }
  14. }
Output:
[5, 1, 1, 1, 2, 2, 2, 2, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4]

Saturday, May 18, 2019

How do you check palindrome?

Problem statement:
How do you check palindrome?
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         isPalindrome(s);
  5.     }
  6.     public static void isPalindrome(String s) {
  7.         String rev = "";
  8.         char c[] = s.toCharArray();
  9.         for (int i = s.length() - 1; i >= 0; i--) {
  10.             rev = rev + c[i];
  11.         }
  12.         if (s.equals(rev))
  13.             System.out.println("Yes");
  14.         else
  15.             System.out.println("No");
  16.     }
  17. }
Output:
Yes
Mehod-II:
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         System.out.println(isPalindrome(s) ? "Yes" : "No");
  5.     }
  6.     public static boolean isPalindrome(String s) {
  7.         int p = s.length() - 1;
  8.         boolean flag = true;
  9.         char c[] = s.toCharArray();
  10.         for (int i = 0; i < s.length() / 2; i++) {
  11.             if (c[i] != c[p]) {
  12.                 flag = false;
  13.                 break;
  14.             }
  15.             p--;
  16.         }
  17.         return flag;
  18.     }
  19. }
Output:
Yes

Tuesday, May 14, 2019

Java String Reverse

Problem statement:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Given a string , print Yes if it is a palindrome, print No otherwise
Constraints:
A will consist at most 50 lower case english letters.
Sample Input:
madam
Sample Output:
Yes
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         System.out.println(isPalindrome(s) ? "Yes" : "No");
  5.     }
  6.     public static boolean isPalindrome(String s) {
  7.         int p = s.length() - 1;
  8.         boolean flag = true;
  9.         for (int i = 0; i < s.length() / 2; i++) {
  10.             if (s.charAt(i) != s.charAt(p)) {
  11.                 flag = false;
  12.                 break;
  13.             }
  14.             p--;
  15.         }
  16.         return flag;
  17.     }
  18. }
Output:
Yes
Method-II:
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         isPalindrome(s);
  5.     }
  6.     public static void isPalindrome(String s) {
  7.         String rev = "";
  8.         for (int i = s.length() - 1; i >= 0; i--) {
  9.             rev = rev + s.charAt(i);
  10.         }
  11.         if (s.equals(rev))
  12.             System.out.println("Yes");
  13.         elset a Palindrome");
  14.     }
  15. }
Output: 
Yes

how do you check whether two strings are anagram to each other?

Problem statement:
Given two Strings S1 and S2. You have to check whether these two strings are anagram to each other?
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class Anagram {
  4.     public static void main(String[] args) {
  5.         String S1 = "LISTEN";
  6.         String S2 = "SILENT";
  7.         if (areAnagram(S1, S2)) {
  8.             System.out.println("Anagram");
  9.         } else {
  10.             System.out.println("Not an Anagram");
  11.         }
  12.     }
  13.     static boolean areAnagram(String s1, String s2) {
  14.         char c1[] = s1.toCharArray();
  15.         char c2[] = s2.toCharArray();
  16.         int n1 = c1.length;
  17.         int n2 = c2.length;
  18.         if (n1 != n2)
  19.             return false;        
  20.         Arrays.sort(c1);
  21.         Arrays.sort(c2);        
  22.         for (int i = 0; i < n1; i++)
  23.             if (c1[i] != c2[i])
  24.                 return false;
  25.         return true;
  26.     }
  27. }
Output: 
Anagram

Sunday, May 12, 2019

How do you implement stack in java

Problem statement:
Stack data structure implementation in java.
  1. public class Stack {
  2.     static final int max = 15;
  3.     int top;
  4.     int a[] = new int[max];
  5.     boolean push(int x) {
  6.         if (top >= (max - 1)) {
  7.             System.out.println("stack overflow");
  8.             return false;
  9.         } else {
  10.             a[++top] = x;
  11.             System.out.println(x + " pushed into stack");
  12.             return true;
  13.         }
  14.     }
  15.     int pop() {
  16.         if (top < 0) {
  17.             System.out.println("stack underflow");
  18.             return 0;
  19.         } else {

  20.             int x = a[top--];
  21.             return x;
  22.         }
  23.     }
  24.     int size() {
  25.         return top + 1;
  26.     }
  27.     boolean isEmpty() {
  28.         return top == -1;
  29.     }
  30.     boolean isFull() {
  31.         return (top == (max - 1));
  32.     }
  33.     int peak() {
  34.         if (!isEmpty())
  35.             return a[top];
  36.         else return -1;
  37.     }
  38.     Stack() {
  39.         top = -1;
  40.     }
  41. }
  42. class MainExecution {
  43.     public static void main(String[] args) {
  44.         Stack s = new Stack();
  45.         s.push(10);
  46.         s.push(20);
  47.         s.push(30);
  48.         System.out.println("size: " + s.size());
  49.         s.push(25);
  50.         System.out.println("new size: " + s.size());
  51.         System.out.println(s.pop() + " popped from stack");
  52.         System.out.println("top element is peak: "+s.peak());
  53.     }
  54. }
Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
size: 3
25 pushed into stack
new size: 4
25 popped from stack
top element peak: 30

what will be the output of the following code?

Problem statement:
what is the output of the following code?
  1. interface Test1 {
  2.     default void run() {
  3.         System.out.println("test1");
  4.     }
  5. }
  6. interface Test2 {
  7.     default void run() {
  8.         System.out.println("test2");
  9.     }
  10. }
  11. public class A implements Test1, Test2 {
  12.     public void run() {
  13.         System.out.println("A");
  14.     }
  15.     public static void main(String args[]) {
  16.         A a = new A();
  17.         a.run();
  18.         Test1 t1 = new A();
  19.         t1.run();
  20.         Test2 t2 = new A();
  21.         t2.run();
  22.     }
  23. }
Output:
A
A
A

how do you write a program to find out total number of square in a chessboard?

Problem statement:
How to find out total number of square in chessboard / any other board of n x n.
  1. class A {
  2.     public static void main(String args[]) {
  3.         int n = 8; // here we can give any value of n
  4.         int n2 = n * (n + 1) * (2 * n + 1) / 6;
  5.         System.out.println(n2);
  6.     }
  7. }
Output:
204
Explanation - for n = 8, it will be 
1 unit - 8 x 8 = 64
2 unit - 7 x 7 = 49
3 unit - 6 x 6 = 36
4 unit - 5 x 5 = 25
5 unit - 4 x 4 = 16
6 unit - 3 x 3 = 9
7 unit - 2 x 2 = 4
8 unit - 1 x 1 = 1
---------------------
total              = 204
Asked in - Synechron technologies

how will you reverse the number?

Problem statement:
how do you reverse the given number?
  1. class A {
  2.     public static void main(String args[]) {
  3.         int n = 243589;
  4.         int r = 0;
  5.         while (n != 0) {
  6.             r = r * 10 + n % 10;
  7.             n = n / 10;
  8.         }
  9.         System.out.println(r);
  10.     }
  11. }
Output:
985342
Asked in - Synechron technologies

what is the output of the program?

Problem statement:
what is the output of the following code?
  1. public class A {
  2.     public static void showMe() {
  3.         System.out.println("A");
  4.     }
  5. }
  6. class B extends A {
  7.     public static void showMe() {
  8.         System.out.println("B");
  9.     }
  10. }
  11. class C extends B {
  12.     public static void showMe() {
  13.         System.out.println("C");
  14.     }
  15. }
  16. class Main {
  17.     public static void main(String[] args) {
  18.         A a = new B();
  19.         a.showMe();
  20.         A a1 = new A();
  21.         a1.showMe();
  22.         B b = new C();
  23.         b.showMe();
  24.         C c = new C();
  25.         c.showMe();
  26.     }
  27. }
Output:
A
A
B
C

Saturday, May 11, 2019

what will be the output of thread problem?

Problem statement:
what will be the output of the following code?
  1. public class Person extends Thread {
  2.     private int count;
  3.     private Person(int count) {
  4.         this.count = count;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         for (int i = 1; i < 4; i++) {
  9.             count = count + 1;
  10.         }
  11.     }
  12.     public static void main(String[] args) {
  13.         Person t = new Person(10);
  14.         t.start();
  15.         System.out.println(t.count);
  16.     }
  17. }
Output: 10
output will vary, will explain the reason soon

what will be the output of thread code?

Problem statement:
what will be the output of the following code?
  1. public class ExecutionFourteen extends Thread {
  2.     private int count;
  3.     private ExecutionFourteen(int count) {
  4.         this.count = count;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         for (int i = 1; i < 4; i++) {
  9.             count = count + 1;
  10.             System.out.println("count inside run() method: " + count + ", thread name: " + Thread.currentThread().getName());
  11.         }
  12.     }
  13.     public static void main(String[] args) {
  14.         ExecutionFourteen t = new ExecutionFourteen(10);
  15.         t.start();
  16.         System.out.println("count inside main() method: " + t.count);
  17.     }
  18. }
Output:
count inside main() method: 10
count inside run() method: 11, thread name: Thread-0
count inside run() method: 12, thread name: Thread-0
count inside run() method: 13, thread name: Thread-0

what will be the output of the following code?

Problem statement:
what will be the output of the following code?
  1. class ExecutionTwelve {
  2.     public void talk() {
  3.         System.out.println("I'm a ExecutionTwelve !");
  4.     }
  5. }
  6. class ExecutionThirteen extends ExecutionTwelve {
  7.     @Override
  8.     public void talk() {
  9.         System.out.println("I'm a ExecutionThirteen !");
  10.     }
  11. }
  12. public class ExecutionEleven {
  13.     public static void main(String[] args) {
  14.         ExecutionTwelve t = new ExecutionThirteen();
  15.         t.talk();
  16.     }
  17. }
Output:
I'm a ExecutionThirteen !

what will happen when you run the following code?

Problem statement:
what is the output for the following code?
  1. class ExecutionTen {
  2.     public void talk() {}
  3. }
  4. public class ExecutionNine {
  5.     public static void main(String[] args) {
  6.         ExecutionTen t = null;
  7.         try {
  8.             t.talk();
  9.         } catch (NullPointerException e) {
  10.             System.out.println("This is NullPointerException !");
  11.         } catch (Exception e) {
  12.             System.out.println("This is an Exception !");
  13.         }
  14.         System.out.println("Everything went fine !");
  15.     }
  16. }
Output:
This is NullPointerException !
Everything went fine !

what will be the output of the following code?

Problem statement:
what will be the output of the following code?

  1. class ExecutionEight {
  2.     public int number = 0;
  3. }
  4. public class ExecutionSeven {
  5.     public void doIt(int i, ExecutionEight e) {
  6.         i = 5;
  7.         e.number = 8;
  8.     }
  9.     public static void main(String[] args) {
  10.         int x = 0;
  11.         ExecutionEight e = new ExecutionEight();
  12.         new ExecutionSeven().doIt(x, e);
  13.         System.out.println(x + " " + e.number);
  14.     }
  15. }
Output:
0 8

what will be the console output when you run the following code?

Problem statement:
what will be the output of the following exception handling code?
  1. public class ExecutionSix {
  2.     public static void throwIt() 
  3.     {
  4.         throw new RuntimeException();
  5.     }
  6.     public static void unsafe() 
  7.     {
  8.         try 
  9.         {
  10.             System.out.println("Unsafe try start !");
  11.             throwIt();
  12.             System.out.println("Unsafe try end !");
  13.         } finally 
  14.         {
  15.             System.out.println("Finally executing !");
  16.         }
  17.     }
  18.     public static void main(String[] args) 
  19.     {
  20.         try 
  21.         {
  22.             unsafe();
  23.         } catch (RuntimeException e) 
  24.         {
  25.             System.out.println("Exception caught !");
  26.         }
  27.     }
  28. }
Output:
Unsafe try start !
Finally executing !
Exception caught !

what will be the console output of the following code? Explain why?

Problem statement:
what will be output and explain why?
  1. public class ExecutionFive {
  2.     public static void main(String[] args) {
  3.         String s1 = "Cat";
  4.         String s2 = "Cat";
  5.         System.out.println(s1 == s2);
  6.     }
  7. }
Output:
true
Explanation - whenever we create an object of String class using 'string literal', string literal means using double quotation mark(" "), then that object stores in a place called string constant pool of heap. So, what JVM does, it checks the object in the string constant pool area, if that object is not available there, then it stores the new object. if the object is already available in string constant pool, then instead of creating new object, it points to the existing object, in this way we are saving the space, time and ultimately good performance.

Below is the memory diagram for string constant pool


what is the output of the of following code? Explain.

Problem statement:
Both the classes ExecutionThree and ExecutionFour are saved in ExecutionThree.java
  1. public class ExecutionThree {
  2.     public static void main(String[] args) {
  3.         System.out.println("ExecutionThree");
  4.     }
  5. }
  6. class  ExecutionFour{
  7.     public static void main(String[] args) {
  8.         System.out.println("ExecutionFour");
  9.     }
  10. }
Output:
Output will depend on how we want to run the class. 
For example:-
If we are running this program in any of the IDE(Integrated Development Environment) without terminal then the IDE will print the output as ExecutionThree

If we are running this program using terminal even in the IDE's terminal, then we must use java tool command.
For it below are the steps:
step-1: javac FileName.java
            javac ExecutionThree.java
step-2: java ClassName
            java ExecutionThree
step-3: output - ExecutionThree
step-4: java ExecutionFour
step-5: output - ExecutionFour

What do you think the output will be for the following code?

Problem statement:
Can you let me know the output of the following code?
  1. public class ExecutionTwo {
  2.     public static void main(String[] args) {
  3.         // primitive data type
  4.         double d1 = 0.8;
  5.         double d2 = 0.8;
  6.         System.out.println(d1 == d2);
  7.         double d3 = 0.8d;
  8.         double d4 = 0.8d;
  9.         System.out.println(d3 == d4);
  10.         double d5 = 0.8D;
  11.         double d6 = 0.8D;
  12.         System.out.println(d5 == d6);
  13.         // Wrapper class
  14.         Double d7 = 0.8;
  15.         Double d8 = 0.8;
  16.         System.out.println(d7.equals(d8));
  17.         Double d9 = 0.8d;
  18.         Double d10 = 0.8d;
  19.         System.out.println(d9.equals(d10));
  20.         Double d11 = 0.8D;
  21.         Double d12 = 0.8D;
  22.         System.out.println(d11.equals(d12));
  23.     }
  24. }
Output:
true
true
true
true
true
true

What do you think the output will be for the following code?

Problem statement:
Can you let me know the output of the following code?
  1. public class ExecutionOne {
  2.     public static void main(String[] args) {
  3.         double d1 = 0.8;
  4.         double d2 = 0.8;
  5.         System.out.println(d1 == d2);
  6.         Double d3 = 0.8;
  7.         Double d4 = 0.8;
  8.         System.out.println(d3 == d4);
  9.     }
  10. }
Output:
true
false

Friday, May 10, 2019

How do you find longest common substring ?

Problem statement:
Given two strings S1 & S2. Find the longest common substring between S1 & S2.
  1. import java.util.ArrayList;
  2. import java.util.List;

  3. public class LongestCommonSubstring {
  4.     public static void main(String[] args) {
  5.         String S1 = "LCLC";
  6.         String S2 = "CLCL";
  7.         //String S3 = "abcdabccab";
  8.         //String S4 = "bcdaccabaabc";
  9.         List<String> com = commonSubstring(S1, S2);
  10.         for (String s: com){
  11.             System.out.println(s);
  12.         }
  13.     }
  14.     public static List<String> commonSubstring(String s1, String s2) {
  15.         Integer match[][] = new Integer[s1.length()][s2.length()];
  16.         int len1 = s1.length();
  17.         int len2 = s2.length();
  18.         int max = Integer.MIN_VALUE;    // max length of the string
  19.         ArrayList<String> result = null;    // result list
  20.         for (int i = 0; i < len1; i++) {    // row iteration
  21.             for (int j = 0; j < len2; j++) {  // column iteration
  22.                 if (s1.charAt(i) == s2.charAt(j)) {
  23.                     if (i == 0 || j == 0)
  24.                         match[i][j] = 1;
  25.                     else
  26.                         match[i][j] = match[i - 1][j - 1] + 1;
  27.                     // if you find a longer common substring re-initialize 
  28. // the max count and update the result list
  29.                     if (match[i][j] > max) {
  30.                         max = match[i][j];
  31.                         result = new ArrayList<String>();
  32.                         // substring starts at i-max+1 & ends at i
  33.                         result.add(s1.substring(i - max + 1, i + 1));
  34.                     }
  35.    // else if you find a common substring with the max length, 
  36.   // store it in the list
  37.                     else if (match[i][j] == max) {
  38.                         result.add(s1.substring(i - max + 1, i + 1));
  39.                     }
  40.                 } else {
  41.                     match[i][j] = 0;
  42.                 }
  43.             }
  44.         }
  45.         return result;
  46.     }
  47. }
Output:
LCL
CLC

How to sort keys in TreeMap by using Comparator with user define objects?

Problem statement:
How to sort keys in TreeMap by using Comparator with user defined objects.
  1. import java.util.Comparator;
  2. import java.util.Set;
  3. import java.util.TreeMap;
  4. public class SortByKeyUserDefine {
  5.     public static void main(String a[]) {
  6.         //By using name comparator (String comparison)
  7.         System.out.println("========= Sort by name ==============");
  8.         TreeMap<Employee, String> tm = new TreeMap<Employee, String>(new MyNameComp());
  9.         tm.put(new Employee("Ram", 3000), "RAM");
  10.         tm.put(new Employee("John", 6000), "JOHN");
  11.         tm.put(new Employee("Crish", 2000), "CRISH");
  12.         tm.put(new Employee("Tom", 2400), "TOM");
  13.         Set<Employee> keys = tm.keySet();
  14.         for (Employee key : keys) {
  15.             System.out.println(key + " ==> " + tm.get(key));
  16.         }
  17.         System.out.println("========= Sort by salary ==============");
  18.         //By using salary comparator (int comparison)
  19.         TreeMap<Employee, String> trmap = new TreeMap<Employee, String>(new MySalaryComp());
  20.         trmap.put(new Employee("Ram", 3000), "RAM");
  21.         trmap.put(new Employee("John", 6000), "JOHN");
  22.         trmap.put(new Employee("Crish", 2000), "CRISH");
  23.         trmap.put(new Employee("Tom", 2400), "TOM");
  24.         Set<Employee> ks = trmap.keySet();
  25.         for (Employee key : ks) {
  26.             System.out.println(key + " ==> " + trmap.get(key));
  27.         }
  28.     }
  29. }

  30. class MyNameComp implements Comparator<Employee> {
  31.     @Override
  32.     public int compare(Employee e1, Employee e2) {
  33.         return e1.getName().compareTo(e2.getName());
  34.     }
  35. }

  36. class MySalaryComp implements Comparator<Employee> {
  37.     @Override
  38.     public int compare(Employee e1, Employee e2) {
  39.         if (e1.getSalary() > e2.getSalary()) {
  40.             return 1;
  41.         } else {
  42.             return -1;
  43.         }
  44.     }
  45. }

  46. class Employee {
  47.     private String name;
  48.     private int salary;
  49.     public Employee(String n, int s) {
  50.         this.name = n;
  51.         this.salary = s;
  52.     }
  53.     public String getName() {
  54.         return name;
  55.     }
  56.     public void setName(String name) {
  57.         this.name = name;
  58.     }
  59.     public int getSalary() {
  60.         return salary;
  61.     }
  62.     public void setSalary(int salary) {
  63.         this.salary = salary;
  64.     }
  65.     public String toString() {
  66.         return "Name: " + this.name + " , Salary: " + this.salary;
  67.     }
  68. }
Output:
========= Sort by name ==============
Name: Crish , Salary: 2000 ==> CRISH
Name: John , Salary: 6000 ==> JOHN
Name: Ram , Salary: 3000 ==> RAM
Name: Tom , Salary: 2400 ==> TOM
========= Sort by salary ==============
Name: Crish , Salary: 2000 ==> null
Name: Tom , Salary: 2400 ==> null
Name: Ram , Salary: 3000 ==> null
Name: John , Salary: 6000 ==> null

How do you sort alphanumeric key of a map OR Sort map by key in java?

Problem statement:
How do you sort alphanumeric key of a map ?

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.TreeMap;
  5. public class SortAlphanumericKeyInMap {
  6.     public static void main(String[] args) {
  7.         Map<String, String> map = new HashMap<>();
  8.         map.put("A1BB", "1");
  9.         map.put("A2CC", "2");
  10.         map.put("A2AA", "2");
  11.         map.put("B1AA", "7");
  12.         Map<String, String> treeMap = new TreeMap<>(map);
  13.         Set<String> keys = treeMap.keySet();
  14.         for (String key : keys) {
  15.             System.out.println(key);
  16.         }
  17.     }
  18. }
Output:
A1BB
A2AA

A2CC
B1AA

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...