Friday, May 10, 2019

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 ?
Method-I:
  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("question1", "1");
  9.         map.put("question9", "2");
  10.         map.put("question4", "2");
  11.         map.put("question6", "7");
  12.         // using TreeMap
  13.         Map<String, String> treeMap = new TreeMap<>(map);
  14.         Set<String> keys = treeMap.keySet();
  15.         for (String key : keys) {
  16.             System.out.println(key);
  17.         }
  18.     }
  19. }
Output:
question1
question4
question6
question9

Method-II:
import java.util.*;
public class SortAlphanumericKeyInMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("question1", "1");
        map.put("question9", "2");
        map.put("question4", "2");
        map.put("question6", "7");
        Set<String> set = map.keySet();
        // This will iterate across the map in natural order of the keys.
        SortedSet<String> keys = new TreeSet<>(set);
        for (String key : keys) {
            System.out.println("sorted key: " + key + " | values: " + map.get(key));
        }
    }
}
Output:
sorted key: question1 | values: 1
sorted key: question4 | values: 2
sorted key: question6 | values: 7
sorted key: question9 | values: 2

Method-III:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Collections;
public class SortAlphanumericKeyInMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("question1", "1");
        map.put("question9", "2");
        map.put("question4", "2");
        map.put("question6", "7");
        Set set = map.keySet();
        // using List
        List keys = new ArrayList(set);
        Collections.sort(keys);
        for (Object key : keys) {
            System.out.println(key);
        }
    }
}
Output:
question1
question4
question6
question9

Saturday, April 27, 2019

what will be the output of the following java code?

Problem statement:
What will be the output of the following java code?
  1. public class ConstructorCall {
  2.     int num = 200;
  3.     public void run(int num) {
  4.         this.num = num;
  5.     }
  6.     public void printE() {
  7.         System.out.println(2 * num);
  8.     }
  9.     public static void main(String[] args) {
  10.         ConstructorCall obj = new ConstructorCall();
  11.         obj.run(10);
  12.         obj.printE();
  13.     }
  14. }
Output: 20

what will be the output of following java code?

Problem statement:
what will be the output of the following java code?
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.HashMap;

  4. public class Solutions{
  5.     public static void main(String[] args) {
  6.         HashMap<Integer, String> m = new HashMap<>();
  7.         m.put(1001,"A");
  8.         m.put(1002,"B");
  9.         Collections.unmodifiableMap(m);
  10.         m.put(1001,"C");
  11.         System.out.println(m);
  12.     }
  13. }
Output: {1001=C, 1002=B}

what will be the output of the following java code?

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
  1. public class Solutions {
  2.     public static void main(String[] args) {
  3.         HashMap<Integer, String> m = new HashMap<>();
  4.         m.put(1001,"A");
  5.         m.put(1002,"B");
  6.         //Collections.unmodifiableMap(m);
  7.         m.put(1001,"C");
  8.         System.out.println(m);
  9.     }
  10. }
Output: {1001=C, 1002=B}

what will be the output of the following code?

Problem statement:
What will be the output of the following code?
  1. import java.util.ArrayList;
  2. public class ArrayListExample {
  3.     public static void main(String[] args) {
  4.         ArrayList list = new ArrayList();
  5.         list.add("a");
  6.         list.add("b");
  7.         list.add(1,"c");
  8.         list.add("d");
  9.         list.add(2,"e");
  10.         System.out.println(list);
  11.     }
  12. }
Output: [a, c, e, b, d]

Which of the following is not the java 8 features?

Problem statement:
which of the following is not java 8 features?
  1. Stream API
  2. Lambda expression
  3. Serialization
  4. Spliterator
  5. Optional class
  6. Functional interfaces
Output: Serialization, it is not a feature of java 8

what is the output of the code?

Problem statement:
Given the code for constructor overloading. What will be the output?
  1. public class ConstructorCall {
  2.     ConstructorCall() {
  3.         System.out.println("default constructor");
  4.     }
  5.     ConstructorCall(int a){
  6.         this();
  7.         System.out.println("parameterized constructor");
  8.         System.out.println(10);
  9.     }
  10.     public static void main(String[] args) {
  11.         ConstructorCall st = new ConstructorCall(3);
  12.     }
  13. }
Output:
default constructor
parameterized constructor
10

Can we have final constructor in java class?

Problem statement:
Can we have final constructor in java class?

No ! we cannot have final constructor in java class.
  1. public class NoFinalConstructor {
  2.     public final NoFinalConstructor() {
  3.         System.out.println("default");
  4.     }
  5.     public static void main(String[] args) {
  6.         NoFinalConstructor st = new NoFinalConstructor();
  7.     }
  8. }
Output: compile time error - modifier 'final' is not allowed.

Can we have private constructor in java?

Problem statement:
Can we have private constructor in java class?

Yes ! we can have private constructor in java class.
  1. public class YesPrivateConstructor {
  2.     private YesPrivateConstructor() {
  3.         System.out.println("default");
  4.     }
  5.     public static void main(String[] args) {
  6.         YesPrivateConstructor st = new YesPrivateConstructor();
  7.     }
  8. }
Output: default

Can we have static constructor in java?

Problem statement:
Can we have static constructor in java?

No ! we cannot have static constructor in java. The purpose of constructor is to initialise the object of the class. So there is no meaning to make constructor as static and thus compiler gives an error at compile time saying modifier 'static' not allowed.
  1. public class NoStaticConstructor {
  2.     public static NoStaticConstructor() {
  3.         System.out.println("default");
  4.     }

  5.     public static void main(String[] args) {
  6.         NoStaticConstructor st = new NoStaticConstructor();
  7.     }
  8. }
Output: compile time error - modifier 'static' is not allowed

Tuesday, April 23, 2019

Java Loop


  1. import jaa.util.Scanner;

  2. public class LoopAlgorithm {
  3.     public static void main(String[] args) {
  4.         Scanner in = new Scanner(System.in);
  5.         int t = in.nextInt();
  6.         for (int i = 0; i < t; i++) {
  7.             int a = in.nextInt();
  8.             int b = in.nextInt();
  9.             int n = in.nextInt();
  10.             int result = 0;
  11.             for (int j = 0; j < n; j++) {
  12.                 if (j == 0) {
  13.                     result = (result +a + (int) (Math.pow(2, j) * b));
  14.                 } else {
  15.                     result = (int) Math.pow(2, j) * b;
  16.                     System.out.println(result+" ");
  17.                 }
  18.             }
  19.             System.out.print("");
  20.         }
  21.         in.close();
  22.     }
  23. }








How do you print table using loop?

Problem Statement: 
Given an integer, N, print its first 10 multiples. Each multiple N x i (where 1<=i<=10) should be printed on a new line in the form: N x i = result.

Input Format
A single integer, N

Constraints
2<=N<=20

Output Format
Print 10 lines of output; each line i (where 1<=i<=10) contains the result of N x i in the form: 
N x i = result.

Sample Input
2

Sample Output
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

  1. public class PrintTable {
  2.     public static void main(String[] args) {
  3.         int N = 2;
  4.         for (int i = 1; i <= 10; i++) {
  5.             System.out.println(N + " x " + i + " = " + N * i);
  6.         }
  7.     }
  8. }

How do you convert int to string using java?

Problem statement:
You are given an integer n, you have to convert it into a string.
If your code successfully converts into a string s the code will print "Good job". Otherwise it will print "Wrong answer".
n can range between 100 to 100 inclusive.
Sample Input 0
100
Sample Output 0
Good job

public class ConvertIntToString {
    public static void main(String[] args) {
        int n = 100;
        //String s = String.valueOf(n);    // method - 1
        //String s = "" + n;                    // method - 2
        String s = Integer.toString(n);     // method - 3
        if (n == Integer.parseInt(s)) {
            System.out.println("Good Job");
        } else {
            System.out.println("Wrong Answer");
        }
    }
}
Output:
Good Job

Saturday, April 13, 2019

Spiral Order Traversal of a Tree [Binary Tree Zigzag Level Order Traversal]

Problem statement:
Write a function to print spiral order traversal of a tree. 
For example.

Input - 
10
J
H
I
A
C
D
F
E
B
G
where 10 is the number of elements in the input array.

Output -
A
BC
FED
GHIJ

Generate Parentheses

Problem statement:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Wednesday, April 3, 2019

How do you add two numbers represented by linked lists ??

Problem statement:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.


Example:


Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

class Node {
    int data;
    Node next;

    Node(int data) {

        this.data = data;
    }

    Node() {

    }

    @Override

    public String toString() {
        return "Node{" +
                "data=" + data +
                ", next=" + next +
                '}';
    }
}

public class AddTwoNumbers {

    static Node head = null;

    public static void main(String[] args) {

        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);

        n1.next = n2;

        n2.next = n3;

        Node n4 = new Node(1);

        Node n5 = new Node(2);
        Node n6 = new Node(3);

        n4.next = n5;

        n5.next = n6;

        Node result = calculate(n1, n4);

        System.out.println(result);
    }

    static Node calculate(Node a, Node b) {

        //        //FIXME: Write your logic
        //  1, 2, 3
        //  1, 2, 3
        int carry = 0;

        while (a != null && b != null) {

            addLast(a.data + b.data);

            a = a.next;

            b = b.next;
        }
        return head;
    }

    public static void addLast(int data) {


        if (head == null) {

            head = new Node(data);
            return;
        }
        Node last = head;
        while (last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }
}

Output:
Node{data=2, next=Node{data=4, next=Node{data=6, next=null}}}

Two Sum [find a pair of index or two sum of index in a list]

Problem statement:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

import java.util.HashMap;
public class Solutions {
    public static void main(String args[]) {
        int nums[] = {2, 7, 11, 15};
        int target = 9;
        int idx[] = twoSum(nums, target);
        for (int index : idx) {
            System.out.print(index + " ");
        }
    }

    public static int[] twoSum(int nums[], int target) {
        HashMap m = new HashMap();
        int arr[] = new int[2];

        for (int i = 0; i < nums.length; i++) {
            Integer val = (Integer) m.get(target - nums[i]);
            if (val == null) {
                m.put(nums[i], i);
            } else {
                arr[0] = val;
                arr[1] = i;
            }
        }
        return arr;
    }
}
Output:    [0,1]
Expected: [0,1]

Wednesday, January 9, 2019

what do you mean by sequence in structured query language [SQL]?

Problem statement: what do you mean by sequence in SQL, can you write a script for creating the sequence & using it into the database?
Sequence is a set of integers 1, 2, 3, 4, 5, ... that are generated on supported by database systems to produce unique values on demand.
  1. A sequence is a user defined schema bound object that generates a sequence of numeric values.
  2. Sequences are frequently used in many databases because many applications requires each row in a table to contain unique value & sequences provides an easy way to generate them.
  3. The sequence of numeric values is generated in an ascending or descending order at defined intervals & can be configured to restart when exceeds max_value.
Syntax:

       CREATE SEQUENCE sequence_name
       START WITH initial_value
       INCREMENT BY increment_value
       MINVALUE minimum_value
       MAXVALUE maximum_value
       CYCLE | NOCYCLE ;

Description:
  • sequence_name: Name of the sequence
  • initial_value: starting value from where sequence starts. initial_value should be greater than      or equal to minimum_value AND less than equal to maximum_value.
  • increment_value: value by which sequence will increment itself. increment_value can be positive or negative.
  • minimum_value: minimum value of the sequence
  • maximum_value: maximum value of the sequence
  • CYCLE: when cycle reaches its set_limit it starts from beginning.
  • NOCYCLE: An exception will be thrown if sequence exceeds its maximum_value
[a] Example: creating sequence in ascending order

      CREATE SEQUENCE sequence1
      start with 1
      increment by 1
      minvalue 0
      maxvalue 1000
      cycle ;
Illustrations: Above script will create a sequence by name sequence1. Sequence will starts from 1 & will be incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding 1000.

[b] Example: creating sequence in descending order

      CREATE SEQUENCE sequence2
      start with 100
      increment by -1
      minvalue 1
      maxvalue 100
      cycle ;
Illustration: Above query will create a sequence named sequence2. Sequence will starts from 100 & should be less than or equal to maximum value & will be incremented by -1 having minimum value 1

[c] Example to use sequence: create a table named employee with columns as id & name.

      CREATE TABLE employee
      (
         ID number(10),
         NAME varchar(20)
      );

     Let's insert values into the table:
     INSERT into employee VALUES(sequence1.nextval, 'Parth');
     INSERT into employee VALUES(sequence1.nextval, 'Madhu');
     INSERT into employee VALUES(sequence1.nextval, 'Rajnish');
     INSERT into employee VALUES(sequence1.nextval, 'Karthik');
      
Here sequence1.nextval will insert id's in id column in a sequence as defined in sequence1

Output:
           ID  |   NAME
           --- ---------------
           1    |   Parth
           2    |   Madhu
           3    |   Rajnish
           4    |   Karthik
      

Wednesday, December 5, 2018

write an algorithm to print prime number from 1 to specific number.

public class PrintAllPrime {
    public static void main(String args[]) {
        int num = 22;
        int count;
        for (int i = 2; i <= num; i++) {
            count = 2;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    count++;
                    break;
                }
            }
            if (count == 2) {
                System.out.print(i + " ");
            }
        }
    }
}
Output:
2 3 5 7 11 13 17 19

Tuesday, November 13, 2018

how do you add a website or ip or url as Trusted sites in internet explorer?

step-1: open internet explorer (ie)
step-2: click tools
step-3: click Internet Options
step-4: click Security tab
step-5: In the Select a Web content zone to specify its current security settings box, click Trusted Sites, and then click Sites

Sunday, October 28, 2018

Can you write an algorithm to check if a string is rotation of each other or not ?

Problem statement:
write an algorithm to check if a string is a rotation of each other or not!!
  1. public class CheckStringRotation {
  2.     public static void main(String args[]) {
  3.         String str1 = "ishaan";
  4.         String str2 = "aanish";
  5.         String temp = str1.concat(str1);
  6.         if (temp.contains(str2)) {
  7.             System.out.println(str2 + " is a rotation of " + str1);
  8.         } else {
  9.             System.out.println(str2 + " is not a rotation of " + str1);
  10.         }
  11.     }
  12. }
Output:
aanish is the rotation of ishaan

Saturday, October 27, 2018

what do you mean by Cryptography ?

Cryptography or cryptology (from Ancient Greek: kryptós "hidden, secret"; graphein, "to write") is the practice and study of techniques for secure communication in the presence of third parties called adversaries. More generally, cryptography is about constructing and analyzing protocols that prevent third parties or the public from reading private messages; various aspects in information security such as data confidentiality, data integrity, authentication, and non-repudiation are central to modern cryptography. Modern cryptography exists at the intersection of the disciplines of mathematics, computer science, electrical engineering, communication science, and physics. Applications of cryptography include electronic commerce, chip-based payment cards, digital currencies, computer passwords, and military communications.

Cryptography prior to the modern age was effectively synonymous with encryption, the conversion of information from a readable state to apparent nonsense.

what do you mean by Blockchain?

A blockchain, is a growing list of records, called blocks, which are linked using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data (generally represented as a merkle tree root hash).

Tuesday, October 16, 2018

what do you mean by synchronized block in java?

Problem statement: Can you explain me about synchronized block in java?

Synchronized block: A block which contains synchronized keyword that is called synchronized block.

#Synchronized block:
  1. class Institute {
  2.     public void classRoom(String facultyName) {
  3.         synchronized (Institute.class) {
  4.             for (int i = 0; i < 10; i++)
  5.                 System.out.println(i + " .class taken by " + facultyName);
  6.             try {
  7.                 Thread.sleep(1000);
  8.             } catch (InterruptedException e) {
  9.                 e.printStackTrace();
  10.             }
  11.         }
  12.     }
  13. }
  14. class MyThread extends Thread {
  15.     Institute inst;
  16.     String factName;
  17.     @Override
  18.     public void run() {
  19.         inst.classRoom(factName);
  20.     }
  21.     MyThread(Institute inst, String name) {
  22.         this.inst = inst;
  23.         this.factName = name;
  24.     }
  25. }
  26. public class SynchronizedExe {
  27.     public static void main(String args[]) {
  28.         Institute inst1 = new Institute();
  29.         Institute inst2 = new Institute();
  30.         MyThread t1 = new MyThread(inst1, "Madhusmita");
  31.         MyThread t2 = new MyThread(inst2, "Ishaan");
  32.         t1.start();
  33.         t2.start();
  34.     }
  35. }
Output:
0 .class taken by Ishaan
1 .class taken by Ishaan
2 .class taken by Ishaan
3 .class taken by Ishaan
4 .class taken by Ishaan
5 .class taken by Ishaan
6 .class taken by Ishaan
7 .class taken by Ishaan
8 .class taken by Ishaan
9 .class taken by Ishaan
0 .class taken by Madhusmita
1 .class taken by Madhusmita
2 .class taken by Madhusmita
3 .class taken by Madhusmita
4 .class taken by Madhusmita
5 .class taken by Madhusmita
6 .class taken by Madhusmita
7 .class taken by Madhusmita
8 .class taken by Madhusmita
9 .class taken by Madhusmita

#Without synchronized block
  1. class Institute {
  2.     public void classRoom(String facultyName) {
  3.         for (int i = 0; i < 10; i++)
  4.             System.out.println(i + " .class taken by " + facultyName);
  5.         try {
  6.             Thread.sleep(1000);
  7.         } catch (InterruptedException e) {
  8.             e.printStackTrace();
  9.         }
  10.     }
  11. }
  12. class MyThread extends Thread {
  13.     Institute inst;
  14.     String factName;
  15.     @Override
  16.     public void run() {
  17.         inst.classRoom(factName);
  18.     }
  19.     MyThread(Institute inst, String name) {
  20.         this.inst = inst;
  21.         this.factName = name;
  22.     }
  23. }
  24. public class SynchronizedExe {
  25.     public static void main(String args[]) {
  26.         Institute inst1 = new Institute();
  27.         Institute inst2 = new Institute();
  28.         MyThread t1 = new MyThread(inst1, "Madhusmita");
  29.         MyThread t2 = new MyThread(inst2, "Ishaan");
  30.         t1.start();
  31.         t2.start();
  32.     }
  33. }
Output:
0 .class taken by Madhusmita
1 .class taken by Ishaan
2 .class taken by Madhusmita
3 .class taken by Ishaan
4 .class taken by Madhusmita
5 .class taken by Ishaan
---------------------------------------
#With synchronized method
  1. class Institute {
  2.     synchronized public void classRoom(String facultyName) {
  3.         for (int i = 0; i < 10; i++)
  4.             System.out.println(i + " .class taken by " + facultyName);
  5.         try {
  6.             Thread.sleep(1000);
  7.         } catch (InterruptedException e) {
  8.             e.printStackTrace();
  9.         }
  10.     }
  11. }
  12. class MyThread extends Thread {
  13.     Institute inst;
  14.     String factName;
  15.     @Override
  16.     public void run() {
  17.         inst.classRoom(factName);
  18.     }
  19.     MyThread(Institute inst, String name) {
  20.         this.inst = inst;
  21.         this.factName = name;
  22.     }
  23. }
  24. public class SynchronizedExe {
  25.     public static void main(String args[]) {
  26.         Institute inst1 = new Institute();
  27.         Institute inst2 = new Institute();
  28.         MyThread t1 = new MyThread(inst1, "Madhusmita");
  29.         MyThread t2 = new MyThread(inst2, "Ishaan");
  30.         t1.start();
  31.         t2.start();
  32.     }
  33. }
Output:
0 .class taken by Madhusmita
0 .class taken by Ishaan
1 .class taken by Madhusmita
1 .class taken by Ishaan
2 .class taken by Madhusmita
2 .class taken by Ishaan

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...