Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Jul 10, 2017

Understanding JVM: Introduction

What are Virtual Machines?

Virtual machine is something which does not have a physical existence, for example, PC calculator. In other words, it is a software simulator of a machine that can perform operation like a physical machine, hence the name - Virtual Machine.

Types of Virtual Machines

There are 2 types of virtual machines:
  1. Hardware based / System based:  These are multiple logical VM, independent of each other, working a single physical VM, example of the same are Kernal Based VM (for Linux), VMware, Cloud Computing, etc. Hardware based VMs results in effective utilization of resources. However it is more related to admin terminology, not programmer.
  2. Application based / Process based / Software based:  These VMs acts as run-time engine to execute a particular programming language application. Example: 
      • JVM - For Java
      • CLR - For .net
      • PVM - For Parrot (scripting language)

Basic architecture Diagram of JVM

JVM is the run time engine to execute Java applications and is part of JRE. It loads and executes application line by lines.

Following is the basic architecture diagram:
Different components in the above diagram will be explained in the coming tutorials. Go to Class Loader Sub System to read first component.

Jul 29, 2016

Difference between SOAP and REST

This is not a tutorial of SOAP or REST web services. It aims at listing out differences between two, which is one of most common interview question. 

Web Services are method of communication between 2 applications over the network. There are two types of web services:
·         SOAP
·         REST

Below are some key differences between the two types of web services:
  • SOAP stands for Simple Object Access Protocol and REST stands for REpresentational State Transfer.
  • SOAP is a protocol while REST is architectural style, on which RESTful web services are build.
  • SOAP uses XML messages for communication while REST is based on HTTP protocol.
  • SOAP response is always in XML format whereas REST can return response in various formats like XML, JSON, HTML.
  • RESTful web service request is much faster than processing a SOAP message because you need to do less parsing.
  • SOAP messages consume more bandwidth than RESTful messages as SOAP has an additional header for every message while RESTful services utilize HTTP header.
  • SOAP web services are language, platform and transport independent whereas RESTful Web services are heavily dependent upon HTTP.
  • RESTful web services utilize URL to identify the desired resources to be accessed while SOAP uses XML messages to identify the desired web procedure or resource to be invoked.
  • SOAP defines its own security whereas RESTful web services inherits security measures from the underlying transport.
  • RESTful services provide a good caching infrastructure over HTTP while SOAP totally ignores web caching mechanism.
  • SOAP uses JAX-WS java API while RESTful web services uses JAX-RS java API.
  • SOAP define standards to be strictly followed in Web Services Description Language (WSDL) that contains and describes the common set of rules to define the messages, bindings, operations and location of the Web service.  RESTful web services has no such standard rules so the service provider and service consumer need to have a common understanding of the context as well as the content being passed along.
  • REST-based implementation is simple compared to SOAP.


In a nutshell, when you're publishing a complex application program interface (API) to the outside world, SOAP will be more useful. But if you need a lightweight API with faster results and simple transactions (i.e., CRUD operations), go with REST.

Hopefully it helps! You can connect with us at +Java Territory to stay updated with latest articles.

Jun 30, 2016

Finding Maximum Subarray, contiguous and non-contiguous

Problem: 
Given an array  of  elements, find the maximum possible sum of a
  1. Contiguous sub-array
  2. Non-contiguous (not necessarily contiguous) sub-array.
Empty sub-arrays/sub-sequences should not be considered.
Solution:
Below is the solution for the problem.
Algorithm 
For maximum contiguous elements sum
1) Make sum and previous_sum equal to first element in arrays, a[0]. 
Now we have to make sure that if sum is negative and Next element is positive, make sum = next element, else add next element to sum. This is done in step 2.
2) Let us assume next element is N, If sum < 0 and N > 0, make sum = N, else make sum = sum + N.
If sum is larger than previous sum, update the previous sum, else if sum < previous sum, and also sum < 0, make sum = next element. This is step 3.
3) If sum >= previous_sum, make previous_sum = sum, else if sum < 0, make sum = N.
4) Repeat steps 2 and 3 for all the elements of input array.
5) Take maximum of sum and previous_sum as the result

For maximum non contiguous elements sum
1) Make sum equal to first element in arrays, a[0]. 
2) If sum is less than 0 and next element, say N is greater than or equal to 0, make sum =N, else,
3) If sum + N > sum, make sum = sum + N, else,
4) If (sum + N < sum) and (sum < N), make sum = N.
5) Repeat step 2, 3 and 4 for each element in the array.

Program:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class ContiguousArraySum {

 /**
  * @param a input array
  * @param n number of elements in the array
  * @return returns the array of size 2, element at 0 gives sum of contiguous elements 
         * while element at 1 gives sum of non-contiguous elements.
  */
 private static long[] findSum(int[] a, int n) {
  long[] result = new long[2];
  long contSum = a[0];
  long prevContSum = a[0];
  long nonContSum = a[0];

  for (int i = 1; i < n; i++) {
   if (contSum < 0 && a[i] >= 0) {
    contSum = a[i];
   } else {
    contSum += a[i];
   }
   if (nonContSum < 0 && a[i] >= 0) {
    nonContSum = a[i];
   } else if (nonContSum + a[i] > nonContSum) {
    nonContSum += a[i];
   } else if (nonContSum < a[i] && nonContSum + a[i] < nonContSum) {
    nonContSum = a[i];
   }
   if (contSum >= prevContSum) {
    prevContSum = contSum;
   } else if (contSum < 0) {
    contSum = a[i];
   }
  }

  result[0] = contSum > prevContSum ? contSum : prevContSum;
  result[1] = nonContSum;
  return result;
 }

}

Please post in the comment section if any thing in code is not clear.

Jun 27, 2016

Program to rotate a 2D matrix

Problem
A 2D matrix, A, of dimension m x n. You have to rotate the matrix 1 time in the clockwise direction and print the resultant matrix. 
Input Format
First Line:  <m>space<n>
Subsequent lines takes Matrix as input.
Example:
Input
3 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Here 3 4 in first line are m(number of rows), and n (number of columns)
Subsequent lines are the Matrix itself.

Expected Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Program:
Our matrix rotation logic does the following:

  1. Rotate elements of first row
  2. Rotate elements of last column
  3. Rotate elements of last row from the remaining rows
  4. Rotate elements of first column from the remaining rows
Source Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class MatrixRotation {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  try {
   // Input number of rows, columns and matrix elements
   int numberOfRows = in.nextInt();
   int numberOfColumns = in.nextInt();
   int matrix[][] = new int[numberOfRows][numberOfColumns];
   for (int i = 0; i < numberOfRows; i++) {
    for (int j = 0; j < numberOfColumns; j++) {
     matrix[i][j] = in.nextInt();
    }
   }

   rotateMatrix(matrix, numberOfRows, numberOfColumns);
   
   // Print rotated matrix
   for (int i = 0; i < numberOfRows; i++) {
    for (int j = 0; j < numberOfColumns; j++) {
     System.out.print(matrix[i][j] + "  ");
    }
    System.out.println();
   }
  } catch (InputMismatchException exception) {
   System.out.println("Invalid input. Only numbers are allowed");
  } finally {
   in.close();
  }
 }

 /**
  * A function to rotate a matrix mat[][] of size M X N.
  * 
  * @param mat matrix of size m x n
  * @param rowSize number of rows in matrix, m
  * @param colSize number of columns in matrix, n
  */
 public static void rotateMatrix(int mat[][], int rowSize, int colSize) {

  // pointers for current row and column
  int currRow = 0;
  int currColumn = 0;
  int prev, curr;

  // p and q defines the number of rows and columns that are not rotated, keeps on decrementing with every iteration
  int p = rowSize;
  int q = colSize;

  while (currRow < p && currColumn < q) {

   if (currRow + 1 == p || currColumn + 1 == q)
    break;

   // store next row's first element, will be copied at first position of current row
   prev = mat[currRow + 1][currColumn];

   // Move elements of first row from the remaining rows
   for (int i = currColumn; i < q; i++) {
    curr = mat[currRow][i];
    mat[currRow][i] = prev;
    prev = curr;
   }
   currRow++;

   // Move elements of last column from the remaining columns
   for (int i = currRow; i < p; i++) {
    curr = mat[i][q - 1];
    mat[i][q - 1] = prev;
    prev = curr;
   }
   q--;

   // Move elements of last row from the remaining rows
   if (currRow < p) {
    for (int i = q - 1; i >= currColumn; i--) {
     curr = mat[p - 1][i];
     mat[p - 1][i] = prev;
     prev = curr;
    }
   }
   p--;

   // Move elements of first column from the remaining rows
   if (currColumn < q) {
    for (int i = p - 1; i >= currRow; i--) {
     curr = mat[i][currColumn];
     mat[i][currColumn] = prev;
     prev = curr;
    }
   }
   currColumn++;
  }

 }

Hopefully you liked the article. Please post your queries in the comments sections. 

Apr 22, 2016

Difference between creating string object via string literal and new String

If you are a Java programmer (which should be the case if you are reading this article), you will know the importance of  knowledge of Strings. Because of their wide usage, handling of Strings become very important. This is also one among the hot topic for interview, specially at the initial stage of your carrier.

In Java, we have two ways of creating String objects, using String literal and creating new String object and this article aims at providing the difference between the 2 options.

Apr 13, 2016

Difference between save(), saveOrUpdate() and persist() in Hibernate Session

save()/ saveOrUpdate()/persist(), these methods are present in Hibernates’s Session interface. These methods serves the purpose of moving object’s state from new/transient to persistent state. However there are some differences between these 3 three APIs – one of popular interview question if you are a java developer. This post aims at listing out these differences.