Thursday, May 31, 2018

Binary search program in java.

Problem statement: What & how do you do binary search ?
  1. A simple approach is to do linear search.
  2. The time complexity of this approach's algorithm is O(n). 
  3. Another approach to perform the same task is using Binary SearchIn case of binary search, array elements must be sorted in ASCENDING order, not in DESCENDING order
  4. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
  5. Binary search is faster than linear search.
  • Algorithm:
  1. Search a sorted array by repeatedly dividing the search interval in half. 
  2. Begin with an interval covering the whole array. 
  3. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. 
  4. Otherwise narrow it to the upper half. 
  5. Repeatedly check until the value is found or the interval is empty.
N.B. - In case of binary search, array elements must be in ascending order. If you have UNSORTED array, you can sort the array using Arrays.sort(arr) method.

METHOD-I:

  1. public class BinarySearchExe {
  2. public static void main(String args[]) {
  3. int arr[] = { 10, 20, 30, 40, 50 };
  4. binarySearchss(arr, 30);
  5. }
  6. public static void binarySearchss(int a[], int key) {
  7. int start = 0, end = a.length - 1;
  8. int mid = (start + end) / 2;
  9. while (start <= end) {
  10. if (key == a[mid]) {
  11. System.out.println("key at index: " + mid);
  12. break;
  13. } else if (key > a[mid]) {
  14. start = mid + 1;
  15. } else {
  16. end = mid - 1;
  17. }
  18. mid = (start + end) / 2;
  19. }
  20. if (start > end) {
  21. System.out.println("key not found!");
  22. }
  23. }
  24. }
Output: 
key at index: 2
Time complexity: O(log n)

METHOD-II:
  1. public class BinarySearchExe {
  2. public static void main(String[] args) {
  3. int a[] = { 10, 20, 30, 40, 50 };
  4. int idx = binarySearch(a, 30);
  5. System.out.println("key at index: " + idx);
  6. }
  7. public static int binarySearch(int a[], int key) {
  8. int start = 0, end = a.length - 1;
  9. while (start <= end) {
  10. int mid = (start + end) / 2;
  11. if (key == a[mid]) {
  12. return mid;
  13. }
  14. if (key < a[mid]) {
  15. end = mid - 1;
  16. } else {
  17. start = mid + 1;
  18. }
  19. }
  20. return -1;
  21. }
  22. }
Output: 
key at index: 2
Time complexity: O(log n)

Saturday, May 26, 2018

How do I run spring boot artifact (jar/war/ear)?

Problem statement: How do I run an artifact using cmd?

  • running an artifact as a package/zip application:

step-1: open cmd
step-2: go to the path where artifact is present in your machine
step-3: fire the following command
            $ java - jar myapp-1.0.0-SNAPSHOT
step-4: enter
step-5: now type the url to access through your browser

  • Using maven plugin:

step-1: open cmd
step-2: go to the path where artifact is present in your machine
step-3: fire the following command
            $ mvn spring-boot:run
step-4: enter
step-5: now type the url to access through your browser

Wednesday, May 23, 2018

how marker interface is handled by JVM in java?

Problem statement: how marker interface or tag interface works in java?

) Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it does some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.


Class vs Object vs Instance

Problem statement: what are the difference between Class, Object & Instance?
In OO Programming, we often hear of terms like “Class”, “Object” and “Instance”; but what actually is a Class / Object / Instance?
In short, An object is a software bundle of related state and behavior. A class is a blueprint or prototype from which objects are created. An instance is a single and unique unit of a class.
Example, we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people).
Let me go into details…
Object
Real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and state (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class
Class is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance
An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

dependency injection (DI) vs inversion of control (IoC) ?

Problem statement: what do you mean by dependency injection (DI) and inversion of control (IoC)?
  • IoC (Inversion of Control): giving control to the container to get instance of an object is called inversion of control, meaning instead i'm creating the object using new operator, let container do that for me.
  • DI (Dependency Injection): way of injecting (providing) properties to an object is called DI.
  • Types of Dependency Injection
  1. Constructor Injection
  2. Setter/Getter Injection - property in xml
  3. Interface Injection (spring does not support)

Benefits of design pattern?

Problem statement: what are the benefits of design pattern?
  1. code re-usability
  2. loosely coupled
  3. reduce total cost
  4. highly maintainability

what is design pattern?

Problem statement: what is design pattern?
  1. A well defined solution to a common problem
  2. International standard approach 
  3. template / approach
  4. language independent(java, .net)

why do we need design pattern?

Problem statement: why do we need design pattern?
  • Solution of commonly occurring problem
  1. how to create a class properly
  2. how to instantiate an object
  3. how to interact between object
  4. how to write loosely coupled code
  5. how to write reusable code

Best Practices of Design Pattern?

Problem statement: what are the best practices of design pattern?
  1. keep it simple
  2. focus on loosely coupled code
  3. design first, code later

Types of design pattern?

Problem statement: what are the types of design pattern?
  • Types of Design Pattern?
  1. Structural: Adapter, Facade
  2. Creational: Singleton, Factory
  3. Behavioral: Iterator, Observer, Stragegy
Structural: deals with structure of class and it is made of variable & methods
Creational: deals with how to instantiate an object
Behavioral: one class interact with other
  • Enterprise level design pattern?
  1. MVC - model view controller
  2. DI - Dependency Injection
  3. DAO - Data Access Object
  4. DTO - Data Transfer Object

Sunday, May 20, 2018

what do you mean by Preorder Traversal in tree?

Problem statement: what do you mean by Preorder traversal in tree?
  • Preorder traversal is defined as follows:
  1. visit the root
  2. traverse the left subtree in preorder
  3. traverse the right subtree in preorder 
  • Recursive Preorder Traversal:
  1. void  PreOrder(BinaryTreeNode root){
  2. if(root !=null){
  3. System.out.println(root.getData());
  4. PreOrder(root.getLeft());
  5. PreOrder(root.getRight());
  6. }
  7. }

what do you mean by tree traversal?

Problem statement: what do you mean by tree traversal?
  1. The process of visiting all nodes of a tree is called tree traversal.
  • Types of tree traversal?
  1. Preorder (DLR) Traversal [D-data, L-left, R-right]
  2. Inorder (LDR) Traversal
  3. Postorder (LRD) Traversal

What do you mean by Tree?

Problem statement: what do you mean by Tree?
  1. Tree is non-linear data structures where each node point to a number of nodes unlike linked list data structure each node points to the next node in a linear fashion.
  2. In tree ADT(Abstract Data Type), order of the element is not important.
  3. If we need ordering information, then linear data structure like linked list, stack, queue, etc can be used.

what are the low/ground level tips for an interview room?

Problem statement: what are the low level points to keep in mind in an interview room?
  1.  Please be dressed in business formals.
  2. While interviewing, please look at the interviewer in the eye and maintain eye contact. If there is a panel, please address your answers to the panel instead only to the person who has asked the question.

Saturday, May 19, 2018

Coconut & sacks(bag) puzzles !!

Problem statement:
An intelligent trader travels from 1 place to another carrying
3 sacks having 30 coconuts each. No sack can hold more
than 30 coconuts. On the way he passes through 30 checkpoints
and on each checkpoint he has to give 1 coconut for each sack he is carrying.
Maximum how many coconuts he can save when he reaches last check point ?


Ans: He will be left with 25 coconuts in 1 sack
  1. First 10 checkpoints = 30 coconuts. Thus, finishing his first sack.
  2. Next 15 checkpoints = 30 coconuts. Thus, finishing his second sack.
  3. Last 5 checkpoints = 5 coconuts. Thus, he still has 25 coconuts in his last sack

Friday, May 18, 2018

What do you mean by spring module?

Problem statement: what are the spring's modules have you used in you projects?



  1. Spring Core module [ Beans, Context ]
  2. Spring Web module [ MVC, Servlet ]
  3. Spring DAO module [ ORM ]
  4. Spring Intergrations [ JMS ]
  5. Spring AOP [ Aspect Oriented Programming ]

what do you mean by spring mvc architecture?

Problem statement : what is the architecture of your project if you use spring mvc pattern?



Step 1: First request will be received by DispatcherServlet
Step 2DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModelAndView object (contains Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

references

List of IT companies?

  1. UnitedHealth Group
  2. Altisource - banking
  3. manhathan 
  4. expedia
  5. UHG
  6. UST global
  7. paypal
  8. Amadeus 
  9. infinite computer sol
  10. ness technology
  11. HARMAN
  12. Oracle
  13. GlobalLogic
  14. Morgan stanley
  15. JP Morgan
  16. Oracle
  17. Cisco
  18. VMware
  19. redBus
  20. Sabre
  21. Altimetrik
  22. payback 
  23. Indegene Private Limited
  24. wipro
  25. Danske IT
  26. Robosoft Technologies
  27. Honeywell
  28. Siemens
  29. sapiens
  30. zapcom
  31. infosys
  32. tcs

How do you display 2nd max, 3rd max, 4th max, ... so on salary from a table? [Co-Related subquery]

Problem statement: display max salary based on certain row's id like 2nd rows, 3rd rows, 4th row, 5th row, ... etc. 
  • CO-RELATED SubQuery: combination of subquery & join
// 2nd max salary:
mysql>SELECT * FROM EMPLOYEE A WHERE 1 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);
output: it will 2nd max salary, because row id begins with 0 & here i'm giving row's id as 1

// 3rd max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE 2 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);

// 4th max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE 3 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);

// Nth max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE N-1 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);
  • Using sub-query:(3rd max salary):
SELECT MIN(EmpSalary) from (
SELECT EmpSalary from Employee ORDER BY EmpSalary DESC LIMIT 3
);

How do you reverse the order of letter in string using SQL?

Problem statement: How do you use reverse function in sql?
Syntax:
SELECT reverse(column_name) FROM Table;

e.g.
id | name | salary
01  ram      2000
02  rani      3000             ==> old_emp
03  lata       1500
04  mary    1700


mysql>SELECT reverse(name) FROM old_emp;
output:
reverse(name)
----------------
mar
inar
atal
yram

How do you insert old table record to new table?

Problem statement: How do you insert data of one table to other table for back up purpose?

Syntax:
INSERT new_table SELECT * FROM old_table;

e.g.

id | name | salary
01  ram      2000
02  rani      3000             ==> old_emp [old_table]
03  lata       1500
04  mary    1700


INSERT new_emp SELECT * FROM old_emp;

id | name | salary
01  ram      2000
02  rani      3000             ==> new_emp [new_table] 
03  lata       1500
04  mary    1700


How do you copy old table to new table within same database?

Problem statement: How do you copy Old table TO New table with whole structures (column name, data type, datatype size, constraints) within the same database !

Syntax:

CREATE TABLE new_table LIKE old_table

e.g.
mysql>show tables;
------------------
tables in my db|
------------------
old_emp

mysql> CREATE TABLE new_emp LIKE old_emp;
QUERY OK, 0 rows affected(0.33sec)

verify:
mysql>show tables;
------------------
tables in my db|
------------------
old_emp
new_emp
------------------

How do you find 2nd max salary from emp table?

Problem statement: how do you find 2nd maximum salary from employee table?

id | name | salary

01  ram      2000
02  rani      3000
03  lata       1500
04  mary    1700

[1] SELECT MAX(salary) FROM EMPLOYEE; 

//output (return): 3000

[2] SELECT MAX(salary) FROM EMPLOYEE where salary < (SELECT MAX(salary) FROM Employee); 

//output (return) - 2000 that is 2nd highest salary

Thursday, May 17, 2018

Sort employee object based on name

Problem statement: Sort employee object based on name !

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;

  5. class Employee {
  6. Integer id;
  7. String name;

  8. Employee(int id, String name) {
  9. this.id = id;
  10. this.name = name;
  11. }

  12. public String toString() {
  13. return "id: " + id + " -name: " + name;
  14. }
  15. }

  16. class SortByEmpName implements Comparator<Employee> {
  17. public int compare(Employee e1, Employee e2) {
  18. return e1.name.compareTo(e2.name);
  19. }
  20. }

  21. public class SortEmployee {

  22. public static void main(String[] args) {
  23. List<Employee> lists = new ArrayList<Employee>();
  24. lists.add(new Employee(23, "ishaan"));
  25. lists.add(new Employee(34, "raju"));
  26. lists.add(new Employee(2, "zebra"));
  27. lists.add(new Employee(43, "ch"));

  28. Collections.sort(lists, new SortByEmpName());
  29. for (Object o : lists) {

  30. System.out.println(o);
  31. }
  32. }
  33. }
Output:

id: 43 -name: ch
id: 23 -name: ishaan
id: 34 -name: raju
id: 2 -name: zebra

Sort employee object base on salary & location both

Problem statement: Sort employee record based on salary & location.

  1. import java.util.List;
  2. import java.util.Arrays;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;

  6. class EmployeeExe1 {
  7. String name;
  8. Double salary;
  9. String location;
  10. EmployeeExe1(String name, Double salary, String location) {
  11. this.name = name;
  12. this.salary = salary;
  13. this.location = location;
  14. }
  15. public String toString() {
  16. return "name: " + name + ", salary: " + salary + ", location: " + location;
  17. }
  18. }

  19. class SortEmpBySalary implements Comparator<EmployeeExe1> {
  20. public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
  21. if (e1.salary.compareTo(e2.salary) > 0) {
  22. return 1;
  23. }
  24. if (e1.salary.compareTo(e2.salary) < 0) {
  25. return -1;
  26. }
  27. return 0;
  28. }
  29. }

  30. class SortEmpByLocation implements Comparator<EmployeeExe1> {
  31. public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
  32. return e1.location.compareTo(e2.location);
  33. }
  34. }

  35. class SortByTwoFields implements Comparator<EmployeeExe1> {
  36. List<Comparator<EmployeeExe1>> empAll;

  37. @SafeVarargs
  38. public SortByTwoFields(Comparator<EmployeeExe1>... e2) {
  39. this.empAll = Arrays.asList(e2);
  40. }

  41. @Override
  42. public int compare(EmployeeExe1 o1, EmployeeExe1 o2) {
  43. for (Comparator<EmployeeExe1> x : empAll) {
  44. int res = x.compare(o1, o2);
  45. if (res != 0) {
  46. return res;
  47. }
  48. }
  49. return 0;
  50. }
  51. }

  52. public class SortEmplyeeBySalLoc {
  53. public static void main(String[] args) {
  54. List<EmployeeExe1> l = new ArrayList<EmployeeExe1>();
  55. l.add(new EmployeeExe1("ishaan", 12000.00, "blr"));
  56. l.add(new EmployeeExe1("raju", 11000.00, "hyd"));
  57. l.add(new EmployeeExe1("ritesh", 9000.00, "del"));
  58. l.add(new EmployeeExe1("nikash", 9000.00, "mum"));

  59. Collections.sort(l, new SortByTwoFields(new SortEmpBySalary(), new SortEmpByLocation()));
  60. for (Object o : l) {
  61. System.out.println(o);
  62. }
  63. }
  64. }
Output:

name: ritesh, salary: 9000.0, location: del
name: nikash, salary: 9000.0, location: mum
name: raju, salary: 11000.0, location: hyd
name: ishaan, salary: 12000.0, location: blr

Tuesday, May 15, 2018

How do you set hibernate second level cache with an example

Problem statement: What is hibernate second level cache?
Caching is facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate also provide this caching functionality, in two layers.
  • Fist level cache: This is enabled by default and works in session scope. Read more about hibernate first level cache.
  • Second level cache: This is apart from first level cache which is available to be used globally in session factory scope.
Above statement means, second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory.
It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
Further, It also means that if you have two instances of session factory (normally no application does that), you will have two cache managers in your application and while accessing cache stored in physical store, you might get unpredictable results like cache-miss.
Region Factory:
We add the Ehcache region factory implementation to the classpath with the following Maven dependency:
   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>5.2.2.Final</version>
</dependency>

Enabling Second-Level Caching:

With the following two properties we tell Hibernate that L2 caching is enabled and we give it the name of the region factory class:
  1. hibernate.cache.use_second_level_cache=true
  2. hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
For example, in persistence.xml it would look like:
1
2
3
4
5
6
7
<properties>
    ...
    <property name="hibernate.cache.use_second_level_cache" value="true"/>
    <property name="hibernate.cache.region.factory_class"
      value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
    ...
</properties>
To disable second-level caching (for debugging purposes for example), just set hibernate.cache.use_second_level_cache property to false.

Making an Entity Cacheable

In order to make an entity eligible for second-level caching, we annotate it with Hibernate specific @org.hibernate.annotations.Cache annotation and specify a cache concurrency strategy.
Some developers consider that it is a good convention to add the standard @javax.persistence.Cacheable annotation as well (although not required by Hibernate), so an entity class implementation might look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Foo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private long id;
    @Column(name = "NAME")
    private String name;
     
    // getters and setters
}
For each entity class, Hibernate will use a separate cache region to store state of instances for that class. The region name is the fully qualified class name.
Cache Concurrency Strategy:

org.hibernate.cache.CacheFactorypublic static final StringNONSTRICT_READ_WRITE"nonstrict-read-write"public static final StringREAD_ONLY"read-only"public static final StringREAD_WRITE"read-write"public static final StringTRANSACTIONAL"transactional"

Based on use cases, we are free to pick one of the following cache concurrency strategies:
  • READ_ONLY: Used only for entities that never change (exception is thrown if an attempt to update such an entity is made). It is very simple and performant. Very suitable for some static reference data that don’t change
  • NONSTRICT_READ_WRITE: Cache is updated after a transaction that changed the affected data has been committed. Thus, strong consistency is not guaranteed and there is a small time window in which stale data may be obtained from cache. This kind of strategy is suitable for use cases that can tolerate eventual consistency
  • READ_WRITE: This strategy guarantees strong consistency which it achieves by using ‘soft’ locks: When a cached entity is updated, a soft lock is stored in the cache for that entity as well, which is released after the transaction is committed. All concurrent transactions that access soft-locked entries will fetch the corresponding data directly from database
  • TRANSACTIONAL: Cache changes are done in distributed XA transactions. A change in a cached entity is either committed or rolled back in both database and cache in the same XA transaction
Cache Management:
If expiration and eviction policies are not defined, the cache could grow indefinitely and eventually consume all of available memory. In most cases, Hibernate leaves cache management duties like these to cache providers, as they are indeed specific to each cache implementation.
For example, we could define the following Ehcache configuration to limit the maximum number of cached Foo instances to 1000:
1
2
3
<ehcache>
    <cache name="org.baeldung.persistence.model.Foo" maxElementsInMemory="1000" />
</ehcache>

Query Cache:


Results of HQL queries can also be cached. This is useful if you frequently execute a query on entities that rarely change.
To enable query cache, set the value of hibernate.cache.use_query_cache property to true:
1
hibernate.cache.use_query_cache=true
Then, for each query you have to explicitly indicate that the query is cacheable (via an org.hibernate.cacheable query hint):
1
2
3
entityManager.createQuery("select f from Foo f")
  .setHint("org.hibernate.cacheable", true)
  .getResultList();

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...