Sunday, December 8, 2019

What is the preferred datatype to store password in java and why?

Problem statement: what would be the better option to choose between char[] array and String.

Answer: Character array i.e. char[] over the String.
Reference

What will be the output of the below java code using volatile keyword?

Problem statement: Given code is
  1. public class Test extends Thread {
  2. private volatile int i = 0;
  3. public int getData() {
  4. return i + 1;
  5. }
  6. public void run() {}
  7. public static void main(String[] args) {
  8. Test t1 = new Test();
  9. t1.start();
  10. System.out.println("First thread: " + t1.getData());
  11. Test t2 = new Test();
  12. t2.start();
  13. System.out.println("Second thread: " + t2.getData());
  14. Test t3 = new Test();
  15. t3.start();
  16. System.out.println("Third thread: " + t3.getData());
  17. }
  18. }
Output:
First thread: 1
Second thread: 1
Third thread: 1

Example for compareTo() method?

How do you sort collection of StringBuffer object in java?

Problem statement: Given the collection of StringBuffer objects.
StringBuffer sb1 = new StringBuffer("Z");
StringBuffer sb2 = new StringBuffer("A");
StringBuffer sb3 = new StringBuffer("P");

You have to sort it either way, meaning natural order or custom order.

Answer:
// ASCENDING ORDER:
  1. import java.util.Comparator;
  2. import java.util.TreeSet;
  3. public class Test {
  4. public static void main(String[] args) {
  5. SortStringBufferObject s = new SortStringBufferObject();
  6. TreeSet<StringBuffer> t = new TreeSet<>(s);
  7. t.add(new StringBuffer("Z"));
  8. t.add(new StringBuffer("A"));
  9. t.add(new StringBuffer("P"));
  10. System.out.println(t);
  11. }
  12. }
  13. class SortStringBufferObject implements Comparator<StringBuffer> {
  14. public int compare(StringBuffer sb1, StringBuffer sb2) {
  15. return sb1.toString().compareTo(sb2.toString());
  16. }
  17. }
Output:
[A, P, Z] 

// DESCENDING ORDER:
  1. import java.util.Comparator;
  2. import java.util.TreeSet;
  3. public class Test {
  4. public static void main(String[] args) {
  5. SortStringBufferObject s = new SortStringBufferObject();
  6. TreeSet<StringBuffer> t = new TreeSet<>(s);
  7. t.add(new StringBuffer("Z"));
  8. t.add(new StringBuffer("A"));
  9. t.add(new StringBuffer("P"));
  10. System.out.println(t);
  11. }
  12. }
  13. class SortStringBufferObject implements Comparator<StringBuffer> {
  14. public int compare(StringBuffer sb1, StringBuffer sb2) {
  15. return sb2.toString().compareTo(sb1.toString());
  16. }
  17. }
Output:
[Z, P, A]
Reference

What is the internal working of Set / HashSet in Java ?

Problem statement: Give an explanation for internal working of Set / HashSet in java.
Answer: Reference

What will be the output when you add custom elements in HashSet?

Problem statement: Given code is
  1. import java.util.HashSet;
  2. class A {}
  3. class B {}
  4. class C {}
  5. public class Test {
  6. public static void main(String[] args) {
  7. HashSet set = new HashSet();
  8. set.add(new A());
  9. set.add(new B());
  10. set.add(new C());
  11. set.add(new A());
  12. System.out.println("Elements: \n" + set);
  13.   System.out.println("Size: " + set.size());
  14. }
  15. }
Answer:
Elements: 
[com.practice.core.C@7852e922, com.practice.core.A@15db9742, com.practice.core.B@6d06d69c, com.practice.core.A@4e25154f]
Size: 4

What will be the output when you add String object in HashSet?

Problem statement: Given code is 
  1. public class Test {
  2. public static void main(String[] args) {
  3. HashSet<String> s = new HashSet<>();
  4. s.add("A");
  5. s.add("B");
  6. s.add("C");
  7. s.add("A");
  8.   System.out.println("Elements: \n" + s);
  9.   System.out.println("Size: " + s.size());
  10.   System.out.println("Objects: " + s);
  11. }
  12. }
Answer:
Elements: 
[A, B, C]
Size: 3
Objects: [A, B, C]

What will be the output when we add elements in collection of ArrayList in java?

Problem statement: In given java code, can you please let me know, what will be the output.
  1. import java.util.ArrayList;
  2. class A {}
  3. class B {}
  4. class C {}
  5. public class Test {
  6. public static void main(String[] args) {
  7. ArrayList list = new ArrayList();
  8. list.add(new A());
  9. list.add(new B());
  10. list.add(new C());
  11.   list.add(new A());
  12. System.out.println(list);
  13.   System.out.println("Size: " + list.size());
  14. }
  15. }
Answer:
[com.practice.core.A@15db9742, com.practice.core.B@6d06d69c, com.practice.core.C@7852e922, com.practice.core.A@4e25154f]
Size: 4

Note: fully_qualified_class_name@hashcode_value

What is the benefits of generic in java?

Problem statement: List out the benefits of generic in java.
  1. type safety
  2. type erasure
  • type safety: what exactly mean of type safety, Compiler guarantee that if correct types are used in correct places means within angular braces then there should not be any ClassCastException in runtime. A use case can be a list of Integer i.e. List<Integer>.If we declare a list in java like List<Integer>, then java guarantees that it will detect and report us any attempt to insert any non-integer type into above list.
  • type erasure: what exactly mean of type erasure, It essentially means that all the extra information added using generics into sourcecode will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior java 5 when generics were not added in language.
Let’s understand with an example.

List<Integer> list = new ArrayList<Integer>(); 
list.add(1000);     //works fine 
list.add("lokesh"); //compile time error 

When we write above code and compile it, we will get an error: “The method add(Integer) in the type List<Integer> is not applicable for the arguments (String)“. Compiler warned us. This is what exactly generics sole purpose i.e. Type Safety.

Second part is getting bytecode after removing second line from above example. If you compare the bytecode of above example with/without generics, then there will not be any difference. Clearly compiler removed all generics information. So, above code is very much similar to below code without generics.

List list = new ArrayList(); 
list.add(1000);

What is the correct and incorrect piece of code for generic representation in Java? [Onward Java 5]

Problem statement: We need to find out the correct pieces of java code.
  1. ArrayList<Integer> l = new ArrayList<>();
  2. ArrayList<Integer> l = new ArrayList<Integer>();
  3. ArrayList<int> l = new ArrayList<int>();
  4. ArrayList<int> l = new ArrayList<>();
  5. LinkedList<Integer> l = new LinkedList<Integer>();
  6. LinkedList<Integer> l = new LinkedList<>();
  7. LinkedList<int> l = new LinkedList<>();
  8. Map<String, Integer> m = new HashMap<String, Integer>();
  9. Map<String, Integer> m = new HashMap<>();
  10. Map<String, int> m = new HashMap<>();
Answer:
  1. Correct- we can keep right angular braces empty
  2. Correct- we can specify the right angular braces data type also
  3. Incorrect-generic support only wrapper class for auto boxing to Object type
  4. Incorrect-generic support only wrapper class for auto boxing to Object type
  5. Correct- we can specify the right angular braces data type also
  6. Correct- we can keep right angular braces empty
  7. Incorrect- generic doen't support primitive data type
  8. Correct - we can specify the right angular braces data type also
  9. Correct - we can keep right angular braces empty
  10. Incorrect- generic doen't support primitive data type

Monday, August 26, 2019

How do you sort the keys in HashMap?

Problem statement:
Write the java code to sort the keys in HashMap.

  1. import java.util.HashMap;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "zz");
  9. m.put("key39", "cc");
  10. m.put("key27", "bb");
  11. Set<String> s = m.keySet();
  12. s = new TreeSet<String>(s);
  13. System.out.println(s);
  14. }
  15. }
Output:
[key12, key27, key39, key45]

How do you sort the values in HashMap?

Problem statement:
Write the java code to sort the values in HashMap.
  1. import java.util.Collection;
  2. import java.util.HashMap;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "zz");
  9. m.put("key39", "cc");
  10. m.put("key27", "bb");
  11. Collection<String> c = m.values();
  12. c = new TreeSet<String>(c);
  13. System.out.println(c);
  14. }
  15. }
Output:
[aa, bb, cc, zz]

Which of the following option will sort the keys in HashMap ?

Problem statement:
Given java code as follows, can you find out the correct option to sort the keys in HashMap?
  1. import java.util.HashMap;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class Test {
  5. public static void main(String[] args) {
  6. HashMap<String, String> m = new HashMap<String, String>();
  7. m.put("key45", "aa");
  8. m.put("key12", "bb");
  9. m.put("key39", "cc");
  10. Set<String> s = m.keySet();
  11.   // code goes here
  12. s = new TreeSet(s);
  13.  }
  14. }
  • Arrays.sort(s);
  • s = new TreeSet(s);
  • Collections.sort(s);
  • s = new SortedSet(s);
Correct option: 
s = new TreeSet(s);
Explanation:
Arrays.sort(s) // sorts for static array 
Collection.sort(s) // sort the List type of object not Set type
s =new SortedSet(s); // SortedSet is an interface

Saturday, August 24, 2019

Write an algorithm to find N’th smallest element in an Unsorted Array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth smallest element in the array.

  1. public class NthSmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.   int thirdSmallest = 3;
  5. int min= nthSmallestElement(a, thirdSmallest );
  6. System.out.println(min);
  7. }
  8. public static int nthSmallestElement(int a[], int n) {
  9. // Sort the given array
  10. Arrays.sort(a);
  11. // Return n'th element in the sorted array
  12. return a[n - 1];
  13. }
  14. }
Output:
3

Write an algorithm to find N’th largest element in an Unsorted Array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth largest element in the array.
  1. public class NthLargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4.                 int thirdLargest = 3;
  5. int max = nthLargestElement(a, thirdLargest);
  6. System.out.println(max);
  7. }
  8. public static int nthLargestElement(int a[], int n) {
  9. // Sort the given array
  10. Arrays.sort(a);
  11. // Return n'th element in the sorted array
  12. return a[a.length - n];
  13. }
  14. }
Output:
4

Write an algorithm to find out the second smallest element in an array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second smallest element in the array.

  1. public class SecondMinElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMin = Integer.MAX_VALUE;
  5. int secondMin = Integer.MAX_VALUE;
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] < firstMin) {
  8. secondMin = firstMin;
  9. firstMin = a[i];
  10. } else if (a[i] < secondMin) {
  11. secondMin = a[i];
  12. }
  13. }
  14. System.out.println("Second min element: " + secondMin);
  15. }
  16. }
Output:
Second min element: 1

Write an algorithm to find out the second largest element in an array.

Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second largest element in the array.
  1. public class SecondMaxElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMax = Integer.MIN_VALUE, // large -ve value
  5.   int secondMax = Integer.MIN_VALUE; // large -ve value
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] > firstMax) {
  8. secondMax = firstMax;
  9. firstMax = a[i]; // a[0] becomes first max
  10. } else if (a[i] > secondMax) {
  11. secondMax = a[i];
  12. }
  13. }
  14. System.out.println(secondMax);
  15. }
  16. }
Output:
10

What is the output of the given java code?

Problem statement:
Given java code, what will be the output of it?
  1. interface Car {
  2. public void startEngine();
  3. }
  4. class MySuzuki implements Car {
  5. public void startEngine() {
  6. System.out.println("MySuzuki");
  7. }
  8. }
  9. class MyFerrari implements Car {
  10. public void startEngine() {
  11. System.out.println("MyFerrari");
  12. }
  13. }
  14. public class OOPSExample {
  15. public static void main(String[] args) {
  16. MyFerrari obj = new MySuzuki();
  17. obj.startEngine();
  18. }
  19. }
Output:
Compile time error at line 16, due to Type mismatch: cannot convert from MySuzuki to MyFerrari

What is the output of the code?

Problem statement:
Given java code, what will be the output of it?
  1. interface Car {
  2. public void startEngine();
  3. }
  4. class MySuzuki implements Car {
  5. public void startEngine() {
  6. System.out.println("MySuzuki");
  7. }
  8. }
  9. class MyFerrari implements Car {
  10. public void startEngine() {
  11. System.out.println("MyFerrari");
  12. }
  13. }
  14. public class OOPSExample {
  15. public static void main(String[] args) {
  16. Car obj = new MySuzuki();
  17. obj.startEngine();
  18. }
  19. }
Output:
MySuzuki

Can you write an algorithm to check palindrome?

Problem statement:
Given a string. Can you check whether it is a palindrome or not?
  1. public class Palindrome {
  2. public static void main(String[] args) {
  3. String s = "abcba";
  4. char c[] = s.toCharArray();
  5. int p = c.length - 1;
  6. for (int i = 0; i < c.length / 2; i++) {
  7. if (c[i] == c[p]) {
  8. p--;
  9. } else {
  10. System.out.println("Not palindrome");
  11. return;
  12. }
  13. }
  14. System.out.println("Palindrome");
  15. }
  16. }
Output:
Palindrome
Time complexity: O(n/2)

How will you find smallest element in an array?

Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the given array?
  1. public class LargestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10 };
  4. int max = Integer.MIN_VALUE;  //-2147483648
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] > max) {
  7. max = a[i];
  8. }
  9. }
  10. System.out.println("max: " + max);
  11. }
  12. }
Output:
max: 5

How will you find smallest element in an array?

Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the smallest element in the given array?
  1. public class SmallestElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 5, 0, -10, -40 };
  4. int min = Integer.MAX_VALUE; // 2147483647
  5. for (int i = 0; i < a.length; i++) {
  6. if (a[i] < min) {
  7. min = a[i];
  8. }
  9. }
  10. System.out.println("min: " + min);
  11. }
  12. }
Output:
min: -40

Wednesday, August 21, 2019

What do you mean by Association, Aggregation and Composition in Java?

What is the difference between Hashtable and ConcurrentHashMap

What is the difference between Hashtable & HashMap?

What are different ways of creating a thread in java?

How do you stop a running thread?

What is heap memory and stack memory in java?

Can we overload constructor in java?

Problem statement:
You are given a code for constructor overloading. What do you think, can we overload the constructor in java?

Ans: Yes.
  1. class A {
  2. A() {
  3. System.out.println("default");
  4. }
  5. A(int id) {
  6. System.out.println("id");
  7. }
  8. A(int id, String name) {
  9. System.out.println("id & name");
  10. }
  11. A(String name, Double salary) {
  12. System.out.println("name & salary");
  13. }
  14. }
  15. public class Sample {
  16. public static void main(String[] args) {
  17. A a = new A();
  18. }
  19. }
Output:
default

Can we override constructor in java?

Problem statement:
You are given a code for constructor overriding. What do you think, can we override the constructor in java?

Ans: No.
  1. class A {
  2. A() {
  3. System.out.println("A of A");
  4. }
  5. }
  6. class B extends A {
  7. A() {
  8. System.out.println("A of B");
  9. }
  10. }
  11. public class Sample {
  12. public static void main(String[] args) {
  13. B b = new B();
  14. }
  15. }
Output:
Return type of method is missing, meaning compiler is treating A() as a method not as a constructor and also compiler is expecting return type for the method A(), because in code there is no return type.

Saturday, August 17, 2019

what will happen when you run the following code?

Problem statement:
Given the java code. what will be the output?
  1. public class Test {
  2. static void test() throws RuntimeException {
  3. try {
  4. System.out.println("test");
  5. throw new RuntimeException();
  6. } catch (Exception ex) {
  7. System.out.println("exception");
  8. }
  9. }
  10. public static void main(String[] args) {
  11. try {
  12. test();
  13. throw new RuntimeException();
  14. } catch (RuntimeException ex) {
  15. System.out.println("runtime");
  16. System.out.println("end");
  17. }
  18. }
  19. }
Output:
test
exception
runtime
end

Friday, August 16, 2019

What is the output of the following code?

Problem statement:
Given the code of java. Find out the output.
  1. public class Test {
  2. static void test() throws RuntimeException {
  3. try {
  4. System.out.println("test");
  5. throw new RuntimeException();
  6. } catch (Exception ex) {
  7. System.out.println("exception");
  8. }
  9. }
  10. public static void main(String[] args) {
  11. try {
  12. test();
  13. } catch (RuntimeException ex) {
  14. System.out.println("runtime");
  15. }
  16.     System.out.println("end");
  17. }
  18. }
Output:
test
exception
end

Sunday, August 11, 2019

What is the output of the following code?

Problem statement: 
Given the code of java. Can you tell me the output of this?
  1. interface Annonymous {
  2.     public int getValue();
  3. }
  4. public class Sample1 {
  5.     int data = 15;
  6.     public static void main(String[] args) {
  7.         Annonymous a = new Annonymous() {
  8.             int data = 5;
  9.             public int getValue() {
  10.                 return data;
  11.             }
  12.             public int getData() {
  13.                 return data;
  14.             }
  15.         };
  16.         Sample1 s = new Sample1();
  17.         System.out.println(a.getValue() + a.getData() + s.data);
  18.     }
  19. }
Output:
compilation error at line number 17 due to a.getData(). Here getData() is not a method of Annonymous interface.

What is the preferred datatype to store password in java and why?

Problem statement: what would be the better option to choose between char[] array and String. Answer: Character array i.e. char[] over ...