The worm

This Article was very interesting and thought of sharing!!

" The Most complicated code ever written!! 

The most sophisticated software in history was written by a team of people, whose names we do not know.
It’s a computer worm. The worm was written, probably, between 2005 and 2010.
Because the worm is so complex and sophisticated, I can only give the most superficial outline of what it does.
This worm exists first on a USB drive. Someone could just find that USB drive lying around, or get it in the mail, and wonder what was on it. When that USB drive is inserted into a Windows PC, without the user knowing it, that worm will quietly run itself, and copy itself to that PC. It has at least three ways of trying to get itself to run. If one way doesn’t work, it tries another. At least two of these methods to launch itself were completely new then, and both of them used two independent, secret bugs in Windows that no one else knew about, until this worm came along.

Java/Rest/Spring

Theory Interview Question Java/J2EE

1. In Spring MVC how to handle exceptions?
  • Controller Based: We annotate our controller with @ExceptionHandlerThis takes exception class as argument.
  • Global Exception Handler: Here we use @ControllerAdvice annotation that we can use with any class to define our global exception handler.
  • HandlerExceptionResolver: Interface that we can implement to create global exception handler

2. What are the annotations would you use?
 @ControllerAdvice,@ExceptionHandler

3. For Global exception handler? What would you use?
@ControllerAdvice

4. For Controller Based?
@ExceptionHandler

5. Get and Load Method?

Find Intersection Between 2 Arrays

Find Intersection Between 2 Arrays

Example:1
Array-1 -- {1,2,3,10,20,5,8}
Array-1 --{20,1,90,30}

Output: 1,20

Example:2
Array-1 -- {10,20,10,10,50,80}
Array-1 --{10,10,10,10}

Output: 10

Steps & Complexity
Step:1 Sort any array[eg:Array-2]
Step:2 Take each element from an array:1, do a binary search for each element in array-1 with Array2
Step:3 If found- add into the set
Step:4 Else increment

Complexity : O(nlogn)

Interface In Java 8

Interface :

It is similar to a class in java, instead, with a keyword as interface. 
Interface used as method declaration, not for implementation untill jdk7

Eg:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
Public interface MyInteface {
 Void m1(String str);
 Void m2(int i);

 // But you cannot write as follows in interface
 /*Void m3(String s){
 System.out.println("You cannot write this way. "); 
     }*/

}




Interface in Java-8 :

Java-8 interface can have STATIC & DEFAULT methods, we can also have method implementation from jdk 8 but has to be default

Eg: Before JAVA-8 

1
2
3
4
5
6
7
Public interface MyInterface{
     Void m1(String str);
     /* Default void m2(String str){
          System.out.println(“Gives an error in prior jav-8 versions. ”);
    } //Gives you an error
  
  */
}



Code In Java-8

Java-8 Functional Interface

Java Functional Interface



If look into some other programming languages like c++, Javascript they are called functional programming languages bcoz, we can write functional and use whenever required.

An interface with only 1 abstract method is called Functional interface.
A new annotation @FunctionalInteface provides us to avoid accidental addition od abstract methods.
Functional interface is long waited and much sought out feature of Java-8 as it enables us to use Lambda expressions to instantiate them.

Being object-oriented is not bad, but when we wanted to implement Runnable we do it as follows

Eg: 


1
2
3
4
5
Runnable r = new Runnable(){
   @Override
   public void run() {
    System.out.println("My Runnable");
   }};

If you notice it, the important logic in under run() method right?

Java-8 lambda expressions allow to help us in writing smaller and cleaner code.


Lambda Expressions:

Lambda expression is way through we can visualize functional programming in java object world.
Objects are base of java prog. Lang. and we can never have a function without an Object


Syntax:  (argument) -> (body)


1
Runnable r1 = () -> System.out.println("My Runnable");


In the above code, Runnable is a functional interface so we can use Lambda.
Since run() has no arguments,  we have no arguments passed.

Advantages of Lambda expressions:
  1. Reduced lines of code.
  2. Pass method into behaviours
  3. High efficiency 

Tell me about yourself

Tell me about yourself


Most of the interviewers ask us to 'tell me about yourself ' and the way you tell about your past projects, roles, and your background could be an icebreaker. If they like it there are 70% chances of getting hired.


Best ways to answer are:

      1. Attempt confidently

Yes, you heard it right!! Tell very confidently, because lack of confidence rises a doubt about your background. If the candidate isn’t confident how can your team and manager trust you?? Not possible right. So go with confidence.


Spring Questions

  • What is Spring Beans??

Java Objects which form the backbone of Spring application and they are assembled, instantiated, and managed by Spring IoC container.

These beans are created with configuration metadata that is supplied to the container, for instance, in the XML <bean/> form definitions.


  • How to provide configuration metadata to the Spring Container?

3 important methods to provide configuration metadata to the Spring Container :

    • Annotation-based configuration
    • Java-based configuration
    • An XML based configuration file

  • Explain the different types of bean scopes supported by Spring?

There are 5 different scopes provided by the Spring Framework:
    • Prototype scope, a single bean definition has any number of object instances.
    • Singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container.
    • Request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware -Spring ApplicationContext.
    • Session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a -web-aware Spring ApplicationContext.
    • Global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.

  • Is Singleton class thread safe in Spring?
    NO


  • Explain Bean lifecycle in Spring framework

The spring container finds the beans definition from XML file, and instantiates the bean and also Spring populates all the properties specified in the bean definition (DI).

    • If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
    • If Bean implements BeanFactoryAware interface, spring passes the bean-factory to setBeanFactory() method.
    • If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesser beforeInitialization() method.
    • If the bean implements IntializingBean, its afterPropertySet() method is called.
    •  If the bean has init method declaration, the specified initialization method is called.
    • If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
    • If the bean implements DisposableBean, it will call the destroy() method.


What happens when you click on SUBMIT button [Spring MVC]

What happens when you click on SUBMIT button 

[Spring MVC] ??



1. When you click on submit the request goes to web.xml
2. Spring has a special servlet called as dispatcher servlet[front controller] 
3. From dispatcher servlet, it will go to the corresponding Controller
4. From controller, it redirects to business object and performs validations 
                              if it passes all the validation it goes to Data access layer 
                              else returns back to the user
5. From DAO it goes to DB 


 Dispatcher servlet  >> vo >> controller >> BO             >>                  DAO  >>  DB                                                                          Validations                                                                         if pass goes to DAO



Dependency Injection

Dependency Injection:


  • DI is a technique where 1object (or static method) supplies dependencies for other objects.i.e. Passing the service to the client, rather than client building the service himself.
  • It is done so that your code can be re-used and can be loosely coupled.
Why to Use Dependency Injection ??

Spring Introduction

Spring:


  • It was developed in 2003 by ROD JOHNSON.
  • It makes easy for the development of JAVAEE application.
  • Spring is a LightWeight framework. It supports other multiple frameworks like JSF, Struts, Hibernate etc.


           Before getting started more about Spring framework is important to know about DI [Dependency Injection and Inversion of control]



Web-Services in Java

Web-Services: Web-service is a service offered by an electronic device to another electronic device, communicating with each other via the World Wide Web, or (specific) a web service implemented in the particular technology or brand, W3C Web Services.
Or
Web services are an open standard (XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for the purpose of exchanging data. Web Services can convert your existing applications into Web-applications.

Why WEB-SERVICES ??

SOA [Service Oriented Architecture]

SOA [Service oriented architecture]

From OOA to SOA, computing and development approach of software services are changing rapidly.

Why SOA ??

Linked List Introduction

Linked List:

Linked List is a data structure used for sorting collection of a data and has the following properties:
§  Successive elements are not connected by pointers
§  Can grow or shrink size during execution of the program
§  It does not waste memory
§  1st node is considered as head
§  Last node is considered as the tail
Main Linked List operations:
Insert:  Inserts elements in the list.
Delete: Delete an element from the list.

Why Linked List??
There are so many data structures which can do the same thing. The important thing is understanding the difference between linked list and arrays. Both linked list and arrays are used to store collection data.
Arrays have a constant access time by using index and size is fixed.
Liked list access time is more but can be growable or resizable.
Linked List types:
A.   Singly Linked List
B.   Doubly Linked List
C.   Circular Linked List

A.   Singly Linked List: Generally linked list means singly linked list. It has a number of node a pointer to next node.

B.   Doubly Linked List: It is also called as two way linked list. It is called so because it can navigate in both the directions.

C.   Circular Linked List: Single and Doubly linked list have ends but circular linked list does not have ends. While traversing a circular linked list we have to careful otherwise we will traverse infinitely.








Strings Introduction



String are most widely used in any programming language. String is basically sequence of characters and. in Java Strings are treated as objects.

string implements serializable, comparable, charsequence


There are 2 ways you can declare String in Java:

Arrays Introduction

Image result for array









As per Wiki "In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula.The simplest type of data structure is a linear array, also called one-dimensional array."


As per above image, the elements starting from 0-9 are called indices and elements are represented below each index.

Applications: 

Find Vowels and Consonants in given String


 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
public class FindOvelsConsonents {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  FindOvelsConsonents o = new FindOvelsConsonents();
  o.findvowelsAndConsonents("NIHAL Is my Name");
  o.findvowelsAndConsonentsUsingContains("NIHAL IS MY NAME");
 }

 int count = 0, count1;

 // ===================Method: 1 ======================
 void findvowelsAndConsonents(String str) {
  String s = str.toLowerCase();
  System.out.println(s);
  for (int i = 0; i < s.length(); i++) {
   if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o'
     || s.charAt(i) == 'u') {
    count++;

   } else if (s.charAt(i) == ' ') {

   } else {
    count1++;
   }
  }
  System.out.println("Ovels are: " + count + ", and  Consonents are: " + count1);

 }

 // ========================Method:2 USING CONTAINS==================
 int vowels;
 int conso;

 void findvowelsAndConsonentsUsingContains(String str) {
  // int[] i = new int[256];
  String strV = "aeiouAEIOU";
  for (int j = 0; j < str.length(); j++) {

   if (strV.contains(Character.toString(str.charAt(j)))) { // Main Logic
    vowels++; // Incrementng vowels count
   } else if (str.charAt(j) == ' ') {
   } else {
    conso++; // Incrementng Consonents count
   }

  }
  System.out.println("Ovels are: " + vowels + " Consonents are:  " + conso);

 }

}

Collections Interview Questions(Theoretical)




1. What is HashMap and Map?


    Map is an interface. Contains methods to manipulate Key-Value based collections. The main methods of Map interface are put(K,V), get(K), Collection<V> values(), Set<K> keySet(), containsKey(), containsValue()

    HashMap is one of implementations of the Map interface based on hashcodes of objects used as keys.

    

2. Difference between HashMap and HashTable? Can we make hashmap synchronized?

    Both implement Map interface. HashTable is synchronized. It is recommended to use HashMap wherever possible. HashTable doesn't allow null keys and values. HashMap allows one null key and any number of null values.

    We can make it synchronized
        Map m = Collections.synchronizedMap(new HashMap());


3. Difference between Vector and ArrayList?


    Both implement List interface. ArrayList is not synchronized. 



4. List vs Set vs Map. Purposes and definitions.


    All three are interfaces.


    List -- storing values in specified order. Provides methods to get the element by its position get(i), finding the element, ListIterator. Known implementations: ArrayList, Vector, LinkedList. The list should be used when the order in which the elements are stored matters.


    Set -- storing only different objects and at most one null element. Known implementations: TreeSet (iterate over the elements in order defined by Comparator, or if the elements implement comparable; provides log(n) performance for basic operations), HashSet -- stores values in buckets defined by their hashcodes. Each bucket is a singly linked list. Provides constant time performance for basic operations. LinkedHashSet


    Map -- for storing key-value pairs. The map cannot contain duplicate keys. Provides three collection views: a set of keys, a collection of values, set of key-value mappings. Know implementations HashMap, EnumMap, TreeMap, LinkedHashMap, WeakHashMap.



5. What is an Iterator?


    It is an interface that contains three methods:  next(), boolean hasNext(), void remove()

    It allows iterating over the collection
    If the class implements iterator then it can be used in foreach loop


6. Pros and cons of ArrayList and LinkedList


    ArrayList -- fast random access.

    LinkedList -- slow random access. Implements Queue interface. Fast deletion of the element.
    If lots of random reads are anticipated use ArrayList.
    If lots of iterations over the whole list and lots of add/delete -- use LinkedList.


7. TreeSet vs LinkedHashSet


    LinkedHashSet is backed by LinkedHashMap. LinkedHashMap is backed by doubly linked list to enforce ordering on the elements contained in the Map.

    If the ordering of the elements in the Set matters to you but you don't want to use a comparator you may use LinkedHashSet since it will enforce order in which the elements were added to the set. Otherwise, use TreeSet


8. Differences between Hashtable, ConcurrentHashMap and Collections.synchronizedMap()


    ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

    Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.


9. How are hash codes computed?


    if hashCode() method is defined then it is called to calculate the hashcode

    if it's not defined the default implementation in Object class does the following:

        public int hashCode() {

            return VMMemoryManager.getIdentityHashCode(this);
        }
        
        
        What is the significance of ListIterator? What is the difference b/w Iterator and ListIterator?

    ListIterator allows to perform iteration both ways (first-->last and last-->first)
    From JavaDoc: ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list


10. Is it possible that hash code is not unique?


    It's totally possible. Actually, a totally valid hashCode() function could look like this


    int hashCode(){ return 57; 

    
    
     What are the advantages of ArrayList over arrays?
    
        1. ArrayList comes with a number of utility methods (e.g. contains, remove, addAll)
        2. Type safety
        3. Dynamic sizing
        On the other hand, arrays are a little bit faster and take less memory (packing). Arrays are also able to contain values of primitive types while ArrayList can only contain Objects.
    

11. The principle of storing data in a hashtable

    
        HashSet. add(element) -> element.hashCode() -> mod bucketsCount -> store
    HashMap. add(key, value) -> key.hashCode() -> mod bucketsCount -> store(value)


12. Can we put two elements with equal hash code to one hashmap?


    Yes.The hash code of the objects doesn't matter, Only the hashcode of keys. But even if you want to put the keys with the same hashcode, it will be ok, since it just means that key-value pairs will be put into the same bucket



13. Iterator and modification of a List. ConcurentModificationException.


    The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. So, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.


    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.


Merge Two Sorted Arrays without extra space

 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
//Merge 2 sorted Arrays where Bigger arrays have a space for smaller Array
//Example: arr1[] = {2,3,4,0,0,0,}
//arr2[] = {5,6,7} Array-2 size is 3, which can be places at array-1
import java.util.Arrays;

public class Merge2SortedArrays {

	public static void main(String[] args) {
		Merge2SortedArrays o = new Merge2SortedArrays();
		int[] arr1 = { 1, 2, 2, 13, 0, 0, 0, 0 };
		int[] arr2 = { 1, 3, 8, 9 };

		o.getSortedArray(arr1, arr2);

	}
	/*
	 * Taking array1(element) and array1(element) comparing if arr1 element is
	 * lesser to arr2 element increment if arr1 element is greater to arr2 element
	 * swap and sort array2
	 * 
	 * Now iterate throught the total array and place sorted 2nd array into 1st
	 * array an print
	 * 
	 */

	public void getSortedArray(int[] arr1, int[] arr2) {

		int arr1Begin = 0;
		int jarr2Begin = 0;
		int temp = 0;
		int findLength = (arr1.length) - arr2.length;
		System.out.println(findLength);
		for (int k = 0; k < findLength; k++) {
			if (arr1[arr1Begin] < arr2[jarr2Begin]) {
				arr1Begin++;
			}
			if (arr1[arr1Begin] >= arr2[jarr2Begin]) {
				temp = arr1[arr1Begin];
				arr1[arr1Begin] = arr2[jarr2Begin];
				arr2[jarr2Begin] = temp;
				arr1Begin++;
				Arrays.sort(arr2);
			}

		}
		System.out.println("1st sorted array: " + Arrays.toString(arr1));
		System.out.println("2nd array is: " + Arrays.toString(arr2));
		System.out.println("*********Merging 2 sorted Arrays**************");
		int temp1 = 0;
		int p = 0;
		for (int m = findLength; m < arr1.length; m++) {

			temp1 = arr1[findLength];
			arr1[findLength] = arr2[p];
			arr2[p] = temp1;
			p++;
			findLength++;

		}
		System.out.println("Final Sorted Array: " + Arrays.toString(arr1));
	}

}
Output: 1st sorted array: [1, 1, 2, 2, 0, 0, 0, 0] 2nd array is: [3, 8, 9, 13] *********Merging 2 sorted Arrays************** Final Sorted Array: [1, 1, 2, 2, 3, 8, 9, 13]

REST Introduction


Image result for Restful web services




















Rest: (Representational State Transfer)
  • It is an architectural style for developing web-services.
  • It is popular (because it is simple). It supports multiple formats like JSON, Text, XML..etc.
  • Rest is also language-independent architectural style, most of the REST-based application can be written in any language (Java, Angular JS, python) as long as the language support web-based request using HTTP.
  • Reason: The reason why REST is popular is supporting multiple programming languages and multiple formats. Before REST developers used SOAP which mainly supports XML and had restrictions. Whereas, REST offers much better style for an approach.

REST: (Main operations)

PUT: Used to create a new resource.
POST: Used to update an existing resource or create a new resource.
GET: Provides a read only access to a resource.
DELETE: Used to remove a resource.