Wednesday, June 20, 2018

How do you do binary search in java?

Problem statement: How will you do for binary search in java?
  1. public class BinarySearchExe {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 5, 6, 7, 9, 10 };
  4. int idx = binarySearch(a, 10);
  5. System.out.println(idx);
  6. } // end of main
  7. 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. } else if (key > a[mid]) {
  14. start = mid + 1;
  15. } else {
  16. end = mid - 1;
  17. }
  18. }
  19. return -1; // if key does not found, return -1
  20. } // end of binarySearch method
  21. }
Output: 6

How do you create tree data structure ?

Problem statement: How will you create tree in java?
  1. /* Class containing left and right child of current
  2. node and data value*/
  3. class Node
  4. {
  5. int data;
  6. Node left, right;

  7. public Node(int data1)
  8. {
  9. data = data1;
  10. left = right = null;
  11. }
  12. }

  13. // A Java program to introduce Binary Tree
  14. class BinaryTree
  15. {
  16. // Root of Binary Tree
  17. Node root;

  18. // Constructors
  19. BinaryTree(int data1)
  20. {
  21. root = new Node(data1);
  22. }

  23. BinaryTree()
  24. {
  25. root = null;
  26. }

  27. public static void main(String[] args)
  28. {
  29. BinaryTree tree = new BinaryTree();

  30. /*create root*/
  31. tree.root = new Node(1);

  32. /* following is the tree after above statement
  33.  
  34.               1
  35.             /   \
  36.           null  null     */

  37. tree.root.left = new Node(2);
  38. tree.root.right = new Node(3);

  39. /* 2 and 3 become left and right children of 1
  40.                1
  41.              /   \
  42.             2      3
  43.           /    \    /  \
  44.         null null null null  */


  45. tree.root.left.left = new Node(4);
  46. tree.root.left.left.right = new Node(9);
  47.         /* 4 becomes left child of 2
  48.                     1
  49.                 /       \
  50.                2          3
  51.              /   \       /  \
  52.             4    null  null  null
  53.            /   \
  54.           null 9
  55.          */
  56. System.out.println(tree.root.right.data);
  57. }
  58. }
Output: 3

Tuesday, June 19, 2018

About GIT UI installation & command

GIT UI installation command:
$> sudo apt-get install git-gui

how to use git ui interface?
step-1: open terminal at the codebase
step-2: type: git gui

Other GIT useful command?
1. git branch
2. git status
3. git fetch && git checkout branchname
4. git stash pop

Saturday, June 16, 2018

What do you mean by final ArrayList?

Problem statement: What is the sense of final ArrayList?

It just mean that you cannot re-assign the reference to new collection object reference. Attempting to do it will lead compile time error. 
e.g. 
[1] - 
final List<String> list = new ArrayList<String>();
list = new ArrayList<String>(); // Since `list' is final, this won't compile
^ 
compile time error here
[2] -
final List<String> linked = new LinkedList<String>();
linked = new LinkedList<String>(); // Since `linked' is final, this won't compile

compile time error here

Note: But I still can add to ArrayList new elements, remove elements and update it.

How do you check whether given trees are isomorphic to each other or not?

Problem statement: Given two trees how do we check whether the trees are isomorphic or not !!

Two binary trees root1 & root2 are isomorphic if they are the same structure. The values of nodes does not affect whether two trees are isomorphic or not.  



  1. int IsIsometric(TreeNode root1, TreeRoot root2){
  2. f(root1 == null && root2 == null)
  3. return 1;
  4. if((root1 == null && root2 != null) || (root1 !=null && root2 == null)) return 0;
  5. return (IsIsometric(root1.getLeft(), root2.getLeft()) && IsIsometric(root1.getRight(), root2.getRight()));
  6. }
Time complexity: O(n), Space complexity: O(n)

How do you create Immutable class in java?

Problem statement: How do you make any java class immutable?
  1. Class must be declared as final (So that child classes can’t be created)
  2. Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
  3. A parameterized constructor
  4. Getter method for all the variables in it
  5. No setters(To not have option to change the value of the instance variable)
  • When exposing methods which modify the state of the class, you must always return a new instance of the class.
  • If the class holds a mutable object:
    • Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through constructor, this is to prevent the clients who pass the object from modifying it afterwards.
    • Make sure to always return a clone copy of the field and never return the real object instance
1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
This principle says that for all mutable properties in your class, do not provide setter methods. Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private
This is another way to increase immutability. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.
3) Don’t allow subclasses to override methods
The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.
4) Special attention when having mutable instance variables
Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.
A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  1. import java.util.Date;
  2.  
  3. /**
  4. * Always remember that your instance variables will be either mutable or immutable.
  5. * Identify them and return new objects with copied content for all mutable objects.
  6. * Immutable variables can be returned safely without extra effort.
  7. * */
  8. public final class ImmutableClass
  9. {
  10.  
  11.     /**
  12.     * Integer class is immutable as it does not provide any setter to change its content
  13.     * */
  14.     private final Integer immutableField1;
  15.     /**
  16.     * String class is immutable as it also does not provide setter to change its content
  17.     * */
  18.     private final String immutableField2;
  19.     /**
  20.     * Date class is mutable as it provide setters to change various date/time parts
  21.     * */
  22.     private final Date mutableField;
  23.  
  24.     //Default private constructor will ensure no unplanned construction of class
  25.     private ImmutableClass(Integer fld1, String fld2, Date date)
  26.     {
  27.         this.immutableField1 = fld1;
  28.         this.immutableField2 = fld2;
  29.         this.mutableField = new Date(date.getTime());
  30.     }
  31.  
  32.     //Factory method to store object creation logic in single place
  33.     public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
  34.     {
  35.         return new ImmutableClass(fld1, fld2, date);
  36.     }
  37.  
  38.     //Provide no setter methods
  39.  
  40.     /**
  41.     * Integer class is immutable so we can return the instance variable as it is
  42.     * */
  43.     public Integer getImmutableField1() {
  44.         return immutableField1;
  45.     }
  46.  
  47.     /**
  48.     * String class is also immutable so we can return the instance variable as it is
  49.     * */
  50.     public String getImmutableField2() {
  51.         return immutableField2;
  52.     }
  53.  
  54.     /**
  55.     * Date class is mutable so we need a little care here.
  56.     * We should not return the reference of original instance variable.
  57.     * Instead a new Date object, with content copied to it, should be returned.
  58.     * */
  59.     public Date getMutableField() {
  60.         return new Date(mutableField.getTime());
  61.     }
  62.  
  63.     @Override
  64.     public String toString() {
  65.         return immutableField1 +" - "+ immutableField2 +" - "+ mutableField;
  66.     }
  67. }

How do I attach(add) javadoc or source code in Eclipse ?

Problem statement: How do I add javadoc or source code in eclipse?
step-1: go to Window -> Preferences -> Java -> Installed JREs 
step-2: edit jre1.8.0 -> expand rt.jar -> click source attachment 
step-3: click external location -> External File -> go to C:\Program Files\Java\jdk1.8.0_91
step-4: select src.zip -> click ok -> click finish -> click ok 

Thursday, June 14, 2018

what is app name's PLACEHOLDER in spring boot properties file

In application.properties file use the following PLACEHOLDER

1.
app.name = any_name_you_want_for_your_app

2
How do you set description PLACEHOLDER in application.properties file
app.description = ${app.name} is a Spring Boot application 

3. How do you set the server context path in application.properties
server.context-path=/${app.name}

4. How do you set port in application.properties file?
server.port = 9091

5. How do you configure external file path in application.properties file?
prefix.jsonFileLocation = /home/ishaan/docs

Placeholder ref

how do you check running process for specific port?

step-1: sudo netstat -nlp | grep :9071
step-2: enter
tcp6       0      0 :::9071                 :::*                    LISTEN      5713/java 
step-3: kill 9071

note: 9 indicates process will kill forcefully

Saturday, June 9, 2018

How do you save a file & exit in vi or vim editor linux

Save a file & exit

Step-1: press esc
Step-2: press :
Step-3: press x
Step-3: enter

2nd Method:
Step-1: press esc
Step-2: press :
Step-3: press wq
Step-4: enter

Wednesday, June 6, 2018

how do you configure/connect remote desktop from Ubuntu to Ubuntu machine?

  1. press super key(windows) in keyboard
  2. type: remote
  3. select Remmina Remote Desktop Client
  4. choose VNC in dropdown
  5. enter the end user machine IP address
  6. click connect
  7. enter the password of end user machine

how do you check IP address in Ubuntu?

  • open terminal & type any of the below command
  1. > ifconfig
  2. > ip add show 

Tuesday, June 5, 2018

what are the tool to check code quality?

Problem statement: can give me the name of the tools that check the code quality?
  1. CheckStyle
  2. SonarCube
  3. JUnit

Monday, June 4, 2018

what do you mean by reflection in java?

Problem statement: what do you mean by reflection in java?

Reflection is an API which is used to examine or modify the behaviour of methods, classes, interfaces at Runtime.
  • The required classes for reflection are provided under java.lang.reflect package.
  • Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
  • Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.

Reflection can be used to get information about –
  1. Class The getClass() method is used to get the name of the class to which an object belongs.
  2. Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.
  3. Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.

what are the LoopHoles of null & NullPointerException

Problem statement: what do you mean by null & NullPointerException?
  • null:
  1. null is reserved literal but not keyword in java [literal mean any constant value that can be assigned to a variable]
  2. we can use null for any object reference variable
  3. if the value of reference variable null means it is not pointing to any object
  4. null is applicable to only for Object types but not for Primitive Type if we are trying to use for the primitive data types then we will get Compile Time Error
  5. null is default value for reference variable [note: make sure you should remember default values concept is applicable only for Instance & Static Variables but not for Local Variable]
  6. System.out.println(null); Compile error - reference to println is ambiguous
String s = null;
System.out.println(s); // valid
System.out.println((String)null); // valid
  • NullPointerException:
7.If we are trying to perform any Operation on the null then we will get Runtime Exception - NullPointerException
8. For any object reference r,
r == null is always false
but null == null is always true
9. for any object reference r,
r.equals(null) is always false
10. null vs NULL vs String s ="";
null & empty both are not same.
there is no concept like NULL in java
11. If an object is no longer required then we can make that object eligible for Garbage Collector by assigning null to all its reference variables.
Student s1 = new Student();
s1 = null;
Now object is eligible for GC

12. In java there are total 53 reserved word out of them 50's are keyword and 3's are reserved literal[true, false, null]

[a]-if reserved words are associated with functionality then it will keyword. e.g. if()...
[b]-if reserved words are just to represent the value then such reserved words are called reserved literals like true, false, null

Sunday, June 3, 2018

LinkedHashSet

Problem statement: what do you mean by LinkedHashSet in collection?
  1. LinkedHashSet is the child class of HashSet
  2. Introduced in 1.4 version
  3. LinkedHashSet is exactly same as HashSet except the following difference
  • HashSet:
  1. The underlying data structure is Hashtable
  2. Insertion order is not preserved
  3. Introduced in 1.2 version
  • LinkedHashSet:
  1. The underlying data structure is Hash table + Linked List(this is hybrid data structure)
  2. Insertion order is preserved
  3. Introduced in 1.4 version
For example:-
  • HashSet:
  1. import java.util.HashSet;
  2. public class HashSetExe {
  3. public static void main(String[] args) {
  4. HashSet h = new HashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }

Output:
true
false
[B, C, D, null, Z, z, 10]

Note: Here, insertion order is not preserved in HashSet

  • LinkedHashSet:
  1. import java.util.LinkedHashSet;
  2. public class LinkedHashSetExe {
  3. public static void main(String[] args) {
  4. LinkedHashSet h = new LinkedHashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }
Output:
true
false
[B, C, D, Z, null, 10, z]
Note: Here, insertion order is preserved in LinkedHashSet

  1. LinkedHashSet is the best choice to develop cache based applications, where duplicates are not allowed and insertion order must be preserved.

Saturday, June 2, 2018

https://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html in Spring MVC and REST

Spring Restful Web Services Example with JSON, Jackson and Client Program

what is the short cut to open the terminal in Linux?

step-1: type Ctrl + Alt + t

How do I install .deb (debian) file in unix/linux?

step-1: open the terminal
step-2: go to the directory where downloaded Debian file is there
step-3: hit the following command

> sudo dpkg - i file-name(this will be the file name as it is)

What are the difference between REST & SOAP?

Problem statement: what are the difference between REST & SOAP?
  • SOAP:
  1. SOAP stands for Simple Object Access Protocol
  2. SOAP can only works with XML format
  3. SOAP uses service interfaces to expose business logic. WSDL(Web service description language) file provides information that can be used to understand what services the web service can offer.
  4. JAX-WS is the java API for SOAP web services.
  5. SOAP does not support error handling
  6. SOAP requires more bandwidth and resource than REST. example
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle=" http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
 <Demo.ishaanoneWebService xmlns="http://tempuri.org/">
   <EmployeeID>int</EmployeeID>
   </Demo.ishaanoneWebService>
 </soap:Body>
</SOAP-ENV:Envelope>
  1. SOAP defines its own security.
  2. SOAP is not lightweight and it require XML parsing
  • REST
  1. REST stands for REpresentational State Transfer
  2. REST can works with different format like XML, JSON, plain text, HTML, etc
  3. REST uses URI to expose business logic. For example, if there is an object which represents the data of an employee hosted on a URL can be accessed as http://demo.ishaanone.com/Employee
  4. JAX-RS is the java API for RESTful web services.
  5. REST support built-in error handling
  6. REST requires less bandwidth and resource than SOAP. for example {"city":"Mumbai","state":"Maharastra"}
  7. RESTful web services inherits security measures from the underlying transpor
  8. REST is lightweight and does not require XML parsing.
  9. REST is useful for restricted devices, such as mobile, for which the overhead of additional parameters are less (e.g., headers)

Friday, June 1, 2018

How many different binary trees are possible with n nodes?

Problem statement: what do you say, how many different binary trees are possible with n nodes?
  • In general, 
  1. if there are n nodes,
  2. then there exist 2n - n different trees
  • example - 
  1. number of node = 3
  2. then different trees = 23 - 3 = 8 - 3 = 5

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