General Notes

Java 8 New features

  • Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
  • Method references provide easy-to-read lambda expressions for methods that already have a name.
  • Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.
  • Repeating Annotations provide the ability to apply the same annotation type more than once to the same declaration or type use.
  • Type Annotations provide the ability to apply an annotation anywhere a type is used, not just on a declaration. Used with a pluggable type system, this feature enables improved type checking of your code.
  • Improved type inference.
  • Method parameter reflection.
  • Lambda expressions enable you to treat functionality as method argument, or code as data

What are lambda expressions ?   

  • is a function (computation that takes parameters and returns a value).
  • Allow functions to be passed around or store like data
  • Allow to pass functions as arguments
  • Default Methods
    • Iterable.forEach(lambda)
      • Sample
        • list.forEach(p -> System.out.println(p));
    • Collection.removeIf(lambda)
      • Sample
        • list.removeIf(p -> "Jones".equals(p.getName()));
    • List.replaceAll(lambda)
      • Sample
        • list.replaceAll(s -> s.toUpperCase());
    • List.sort(lambda)
      • Sample
        • list.sort(Comparator.comparing(Person::getName));
        • list.sort(comparing(Person::getAge).thenComparing(Person::getName));
  • Sample
List<Person> list = ....;
Collections.sort(list, (p1,p2) -> p1.getName().compareTo(p2.getName()))

Ideal use case

    Social networking administrator wants to perform certain action over some given members.

Reflection

  • The ability of a computer program to examine (see type introspection) and modify its own structure and behavior (specifically the values, meta-data, properties and functions) at runtime

What is a Functional interface ?

  • Any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)

Annotations what they are and what they are useful for ?

  • Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose

  • Java annotations are typically used for the following purposes:

    • Compiler instructions
    • Build-time instructions
    • Runtime instructions

Sample

@Entity
public class Vehicle {

    @Persistent
    protected String vehicleName = null;

    @Getter
    public String getVehicleName() {
        return this.vehicleName;
    }

    public void setVehicleName(@Optional vehicleName) {
        this.vehicleName = vehicleName;
    }

    public List addVehicleNameToList(List names) {

        @Optional
        List localNames = names;

        if(localNames == null) {
            localNames = new ArrayList();
        }
        localNames.add(getVehicleName());

        return localNames;
    }

}

What is the difference between overloading and overriding?

  • The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required. Overriding is all about giving a specific implementation to the inherited method of parent class.

  • private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.

  • Return type of method does not matter in case of method overloading, it can be same or different. However in case of method overriding the overriding method can have more specific return type.

  • Argument list should be different while doing method overloading. Argument list should be same in method Overriding

Overloading Sample

//A class for adding upto 5 numbers
class Sum
{
    int add(int n1, int n2)
    {
        return n1+n2;
    }
    int add(int n1, int n2, int n3)
    {
        return n1+n2+n3;
    }
    int add(int n1, int n2, int n3, int n4)
    {
        return n1+n2+n3+n4;
    }
    int add(int n1, int n2, int n3, int n4, int n5)
    {
        return n1+n2+n3+n4+n5;
    }
    public static void main(String args[])
    {
     Sum obj = new Sum();
     System.out.println("Sum of two numbers: "+obj.add(20, 21));
     System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
     System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
     System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
    }
}

Overriding Sample

package beginnersbook.com;
class CarClass
{
    public int speedLimit()
    {
        return 100;
    }
}
class Ford extends CarClass
{
    public int speedLimit()
    {
        return 150;
    }
    public static void main(String args[])
    {
     CarClass obj = new Ford();
     int num= obj.speedLimit();
     System.out.println("Speed Limit is: "+num);
    }
}

What access modifiers do you know? Can you explain them for Class, Methods and for instance and local variables?

  Class Methods Instance Variable Local Variable
private A class cannot be private except nested class. Accesible within the same class Accesible within the same class Does not make sense
default Accesible within the same package   Accesible within the same package  
protected A class cannot be protected except nested class. accessible within package and outside the package but through inheritance only accessible within package and outside the package but through inheritance only  
public accessible everywhere accessible everywhere accessible everywhere  

How would you implement the equals method? 

When implementing equals, fields are compared differently, according to their type:

  • object fields, including collections : use equals
  • type-safe enumerations : use either equals or == (they amount to the same thing, in this case)
  • possibly-null object fields : use both == and equals
  • array fields : use Arrays.equals
  • primitive fields other than float or double : use ==
  • float : convert to int using Float.floatToIntBits, then use ==
  • double :  convert to long using Double.doubleToLongBits, then use ==

All objects have both identity (the object's location in memory) and state (the object's data). The == operator always compares identity. The default implementation of equals compares identity as well.

Sometimes the default implementation of equals has the desired behaviour (as in a type-safe enumeration, for example), but equals should usually compare state, not identity. This is particularly true for "data-centric" classes which map to database records.

hashCode and equals are closely related:

  • if you override equals, you must override hashCode.
  • hashCode must generate equal values for equal objects.
  • equals and hashCode must depend on the same set of "significant" fields. You must use the same set of fields in both of these methods. You are not required to use all fields. For example, a calculated field that depends on others should very likely be omitted from equals and hashCode.
  • Objects placed in a List, Set, or Map (as either a key or value) should have an appropriate definition of equals

In an equals method, it's usually worthwhile to order field comparisons such that the most significant comparisons are performed first. That is, fields most likely to differ should be evaluated first. This allows the && "short-circuit" logical operator to minimize execution time.

What is the general contract that should follow the equals method? 

Equals should usually compare state

Reference

What is the general contract that should follow the hashcode method? 

hashCode must generate equal values for equal objects.

Reference

What is the difference between equals and hashcode? What is its usage in java? 

Equals returns a boolean while hashcode returns a value, both are used to compare objects. These methods are very important in collections to compare objects, for example, two "equals" objects must not be twice in a Map "collection".

Common Errors while overriding equals in Java

  • not doing null check for member variables which ultimately results in NullPointerException in Java during equals() invocation.
  • not overriding hashCode method in Java and only overriding equals() methodYou must have to override both equals() and hashCode() method in Java, otherwise your value object will not be able to use as key object in HashMap because working of HashMap is based on equals() and hashCode.
  • not keeping equals() and compareTo() method consistent which is a non formal requirement in order to obey contract of Set to avoid duplicates. SortedSet implementation like TreeSet uses compareTo to compare two objects like String and if compareTo() and equals() will not be consistent than TreeSet will allow duplicates which will break Set contract of not having duplicates.

Difference between Set, List and Map

Set, List and Map are interfaces that defines core contract

Set

  • It can not contains duplicates
  • Unordered collection
  • TreeSet implementation maintains a sorting order, imposed by using Comparator or Comparable
  • Allow just one null element (since it does not allow duplicated!)

List

  • Allow duplicates
  • Ordered collection
  • Allows null elements

Map

  • Contain Key and Value: Both can be objects and the value can be repeated through the Map "implementation", but the key shall be unique
  • TreeMap implementation maintains a sorting order, imposed by using Comparator or Comparable
  • Allow several null values, but just one null key
  • Hashtable do not allow null key or values
  • HashMap allows null values and a null key

Queues

  • A collection that order its elements in a specific way, typically in a first input first output mode, nevertheless other sorting ways are possible

When to use List, Set and Map in Java

Based upon our understanding of difference between Set, List and Map we can now decide when to use List, Set or Map in Java.

1) If you need to access elements frequently by using index, than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know index.

2) If you want to store elements and want them to maintain an order on which they are inserted into collection then go for List again, as List is an ordered collection and maintain insertion order.

3) If you want to create collection of unique elements and don't want any duplicate than choose any Set implementation e.g. HashSet, LinkedHashSet or TreeSet. All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.

4) If you store data in form of key and value than Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need. In order to choose between first two see difference between HashSet and HashMap in Java.

What is the difference between Comparator and Comparable interface? Give some example.

Comparable

  • Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.
  • If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.

  • Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Sample

public class Country implements Comparable{
    @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
    }
}

Comparator

Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example:

public class CountrySortByIdComparator implements Comparator<Country>{
    @Override
    public int compare(Country country1, Country country2) {
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0;
    }
}

Using Comparator interface,we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code. For example:

        Country indiaCountry=new Country(1, 'India');
        Country chinaCountry=new Country(4, 'China');
        Country nepalCountry=new Country(3, 'Nepal');
        Country bhutanCountry=new Country(2, 'Bhutan');

        List<Country> listOfCountries = new ArrayList<Country>();
        listOfCountries.add(indiaCountry);
        listOfCountries.add(chinaCountry);
        listOfCountries.add(nepalCountry);
        listOfCountries.add(bhutanCountry);

//Sort by countryName
Collections.sort(listOfCountries,new Comparator<Country>() {
   @Override
   public int compare(Country o1, Country o2) {
       return o1.getCountryName().compareTo(o2.getCountryName());
   }

What is an inner class ? What kind of inner classes exists?

Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:

  • Static member classes
public class Outer{
   static class Nested_Demo{
      public void my_method(){
         System.out.println("This is my nested class");
      }
   }
   
   public static void main(String args[]){
      Outer.Nested_Demo nested = new Outer.Nested_Demo();    
      nested.my_method();
   }  
}
  • Member classes
class Outer_Demo{
   int num;
   //inner class
   private class Inner_Demo{
      public void print(){       
         System.out.println("This is an inner class");
      }
   }
   //Accessing he inner class from the method within
   void display_Inner(){
      Inner_Demo inner = new Inner_Demo();
      inner.print();
   }
}
   
public class My_class{
   public static void main(String args[]){
      //Instantiating the outer class 
      Outer_Demo outer = new Outer_Demo();
      //Accessing the display_Inner() method.
      outer.display_Inner();
   }

}
  • Method Local inner classes
public class Outerclass{
   
   //instance method of the outer class 
   void my_Method(){
      int num = 23;
   
      //method-local inner class
      class MethodInner_Demo{
         public void print(){
            System.out.println("This is method inner class "+num);      
         }   
      }//end of inner class
      
      //Accessing the inner class
      MethodInner_Demo inner = new MethodInner_Demo();
      inner.print();
   }
   
   public static void main(String args[]){
      Outerclass outer = new Outerclass();
      outer.my_Method();            
   }
}
  • Anonymous classes
abstract class InventedClass{
   public abstract void returnString();
}

public class AnonymousClass {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      
      InventedClass invented = new InventedClass() {
         public void returnString (){
            System.out.println("Hello Lovely World!!!");
         }
      };
      invented.returnString();
   }
}
  • Sample of an anonymous class passed as parameter
//interface
interface Message{
   String greet();   
}

public class My_class {
   //method which accepts the object of interface Message
   public void displayMessage(Message m){
      System.out.println(m.greet() +", This is an example of anonymous inner calss as an argument");     
   }

   public static void main(String args[]){
      //Instantiating the class
      My_class obj = new My_class();
      
      //Passing an anonymous inner class as an argument
      obj.displayMessage(new Message(){
         public String greet(){
            return "Hello";         
         }
      });
   }
}​

Let's take a quick look at each in turn.

Briefly, a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Like a static member class, a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

Finally, an anonymous class is a local class that has no name.

To answer your specific question, I'll focus on the member and anonymous inner classes since those are the ones you'll likely encounter and use. To me, the advantages of inner classes can be divided into three categories: an object-oriented advantage, an organizational advantage, and a call-back advantage.

Reference

What are the final, finally and finalize keywords for? Explain its usage in Classes, methods, instance and local variables.

 

Final

Variable

Final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change

Method

Final can also make a method not "overrideable"

public final String toString() {  return "NULL"; }

Class

Final can also make a class not "inheritable". i.e. the class can not be subclassed.

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

Finally

finally is used in a try/catch statement to execute code "always"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Finalize

Finalize is called when an object is garbage collected. You rarely need to override it. An example:

public void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}

How could you achieve the inmutability in a Class?

1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

2. Make all fields final and private.

3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

4. If the instance fields include references to mutable objects, don't allow those objects to be changed:

  • Don't provide methods that modify the mutable objects.
  • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
final public class ImmutableRGB {

    // Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;

    private void check(int red,
                       int green,
                       int blue) {
        if (red < 0 || red > 255
            || green < 0 || green > 255
            || blue < 0 || blue > 255) {
            throw new IllegalArgumentException();
        }
    }

    public ImmutableRGB(int red,
                        int green,
                        int blue,
                        String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }

    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }

    public String getName() {
        return name;
    }

    public ImmutableRGB invert() {
        return new ImmutableRGB(255 - red,
                       255 - green,
                       255 - blue,
                       "Inverse of " + name);
    }
}

Why String is made as final an Immutable?

1. Requirement of String Pool

String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

The following code will create only one string object in the heap.

String string1 = "abcd";
String string2 = "abcd";

2. Caching Hashcode

The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.

3. Facilitating the Use of Other Objects

To make this concrete, consider the following program:

HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));

for(String a: set)
  a.value = "a";

​In this example, if String is mutable, it's value can be changed which would violate the design of set (set contains unduplicated elements). This example is designed for simplicity sake, in the real String class there is no value field.

4. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Here is a code example:

boolean connect(string s){
    if (!isSecure(s)) {
throw new SecurityException();
}
    //here will cause problem, if s is changed before this by using other references.   
    causeProblem(s);
}

5. Immutable objects are naturally thread-safe

Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminate the requirements of doing synchronization.

 

In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.

What is the serializable interface for?

It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

What is the meaning of signature in java?

A type signature or type annotation defines the inputs and outputs for a function, subroutine or method. A type signature includes the function's return type, the number of arguments, the types of arguments, or errors it may pass back.

What is the difference between Autoboxing and Unboxing?

Autoboxing

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Unboxing

Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

 

What is the StringBuilder for? What is the difference with StringBuffer?

Both are similar, but StringBuilder is not thread safe.

  String StringBuffer StringBuilder
Storage Area Constant String Pool Heap Heap
Modifiable No (immutable) Yes( mutable ) Yes( mutable )
Thread Safe Yes Yes No
Performance Fast Very slow Fast

Reference

What kind of sorting Java provides?

We have Comparable and Comparator interfaces.

What is a collection? What kind of collections exist? Explain differences

A collection is a structure that can store several elements.

There are three types of collections:

  • Lists
  • Sets
  • Maps

What is the difference between ArrayList, Vector and an Array?

ArrayList vs Vector

Synchronization

ArrayList is non-synchronized which means multiple threads can access the ArrayList at the same time.

Vector is synchronized, one thread at a time.

Resize

ArrayList grow by half of its size when resized 

Vector doubles the size of itself by default when grows

Array is static in size that is fixed length data structure.

Multidimensional

Array can be multidimensional

ArrayList is single dimensional

What is the difference between HashMap and HashTable?

1. Synchronization or Thread Safe :  This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
When to use HashMap ?  answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications. 

2. Null keys and null values :  Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.

3. Iterating the values:  Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.

4.  Fail-fast iterator  : The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.
According to Oracle Docs,  if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModification Exception.
Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.We have already explained the difference between iterator and enumeration.

5. Performance :  Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized  object like Hashtable in single threaded environment.

6. Superclass and Legacy :  Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map"  abstract data type.

Generics

What is generics? What is for? When do you use them?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Code that uses generics has many benefits over non-generic code:

Stronger type checks at compile time.
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Elimination of casts.
The following code snippet without generics requires casting:

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

When re-written to use generics, the code does not require casting:

List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);   // no cast

Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

WHAT IS AN EXCEPTION IN JAVA?

It is an event that occurs during the execution of a program that disrupts the normal flow of instructions

HOW CAN YOU CREATE A CUSTOM EXCEPTION?

Creating a class that is a subclass of java.lang.Exception (for a checked exception) or java.lang.RuntimeException (for an unchecked exception)

HOW CAN WE HANDLE CHECKED EXCEPTIONS?

We can handle checked exceptions in two ways

  • Throwing the exception
  • Implementing try/catch block

WHAT IS THE DIFFERENCE BETWEEN CHECKED AND UNCHECKED EXCEPTIONS?

Checked exceptions

Those subject to the Catch or Specify requirement. Checked at compilation time, directly related to the application. If there is no try catch there will be an compilation error. These are subclasses of java.lang.Exception

Sample :

    User enters a non existent file

  • java.io.FileReader
  • FileNotFoundException
  • ParseException    

Unchecked exceptions

Those that are not subject to the Catch or Specify Requirement. These are not evaluated at compilation time. They are sub classes of java.lang.RuntimeException

Sample :

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException

Runtime exceptions

Those that are not subject to the Catch or Specify Requirement. Not checked at compilation time, directly related to the application logic errors or improper use of an API. They are sub classes of java.lang.RuntimeException

Samples :

   If a logic allows passing a null to a constructor that expects an object

  • NullPointerException
  • IllegalArgumentException

Error exceptions

Those that are not subject to the Catch or Specify Requirement. Not directly related to the application. They are sub classes of java.lang.Error class

Abnormal condition with the application OutOfMemoryError or VirtualMachineError

Sample :

    Unable to read an existend file because of a hardware problem

  • OutOfMemoryError
  • VirtualMachineError

HOW DOES SPRING IMPLEMENTS ADVICE ?

Spring implements advice through 4 possible interfaces, a proxy bean and its configuration at the application context

org.springframework.aop.AfterReturningAdvice
org.springframework.aop.MethodBeforeAdvice
org.springframework.aop.ThrowsAdvice;
org.aopalliance.intercept.MethodInterceptor

Advice can also be accomplished with AspectJ which allow the use of Advice through anotations

WHICH ARE THE ISOLATION LEVELS THAT SPRING TRANSACTIONS USES ?

  • READ_UNCOMMITTED : A transaction can read uncommitted data of other transactions
  • READ_COMMITTED   : A transaction can't read uncommitted data of other transactions
  • REPEATABLE_READ  : States that if a transaction reads a record from the DB multiple times, the result is always the same
  • SERIALIZABLE     : A transaction executes with locking at all levels (read, range and write), do not allow concurrency
  • DEFAULT          : Uses default isolation level of the data source

WHICH IS THE DIFFERENCE BETWEEN INDEX AND CLUSTERED INDEX ?

  • A clustered index determines the order in which the rows of the table will be stored on disk – and it actually stores row level data in the leaf nodes of the index itself. A non-clustered index has no effect on which the order of the rows will be stored.
  • Using a clustered index is an advantage when groups of data that can be clustered are frequently accessed by some queries. This speeds up retrieval because the data lives close to each other on disk. Also, if data is accessed in the same order as the clustered index, the retrieval will be much faster because the physical data stored on disk is sorted in the same order as the index.
  • A clustered index can be a disadvantage because any time a change is made to a value of an indexed column, the subsequent possibility of re-sorting rows to maintain order is a definite performance hit.
  • A table can have multiple non-clustered indexes. But, a table can have only one clustered index.
  • Non clustered indexes store both a value and a pointer to the actual row that holds that value. Clustered indexes don’t need to store a pointer to the actual row because of the fact that the rows in the table are stored on disk in the same exact order as the clustered index – and the clustered index actually stores the row-level data in it’s leaf nodes.

WHEN AN INDEX COULD BE REDUNDANT ?

An index can be redundant when there is a second index that evaluates to the same rows as the initial index does

WHAT IS A STORED PROCEDURE ?

It is like a script (subprogram) for SQL, being used to perform defined operations 

DECLARE
   a number;
   b number;
   c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
   IF x < y THEN
      z:= x;
   ELSE
      z:= y;
   END IF;
END; 

BEGIN
   a:= 23;
   b:= 45;
   findMin(a, b, c);
   dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/

WHAT IS THE LIFE CYCLE OF A THREAD ?

Threads have these states

  • New
  • Runnable
  • Running
  • Waiting
  • Dead

WHAT DOES OBJECT.WAITH() AND OBJECT.NOTIFY() DO ?

El método wait de la clase Thread hace que el subproceso espere en un estado Not Runnable hasta que sea avisado (notify) de que continúe. El método notify informa al subproceso en espera que continúe su ejecución. notifyAll es similar a notify excepto que se aplica a todos los subprocesos en estado de espera

WHICH OBJECT'S MONITOR IS ACQUIRED WHEN A SYNCHRONIZED BLOCK/METHOD IS CALLED ?

It will be the lock of the current instance of the class

IN JAVA CONCURRENCY TERMS, WHAT DOES A DEADLOCK LOOK LIKE ?

two (or more) threads are each waiting on the other thread to free a resource that it has locked, while the thread itself has locked a resource the other thread is waiting on

WHAT IS CACHE POLICY ? GIVE EXAMPLES. HOW TO APPLY IN A REST SERVICE ?

WHAT IS ACID ?

Set of properties that guarantee that database transactions are processed reliably. ACID stands for

Atomicity : requires transactions to be all or nothing
Consistency : ensures transaction to go from one valid state to another
Isolation : ensures that concurrent transactions results in a system state that would be obtained if transactions were executed serially
Durability : ensures that when a transaction has been commited it will remain so, even in the event of power loss, crashes or errors

WHAT IS AN ISOLATION LEVEL ?

Its something that defines how the changes made to a DB by a transaction affect other concurrent transactions and also when such data change becomes available to other transactions

WHAT IS AN INDEX ?

It is a reference to a row, used to improve performance

What is the difference between a process and a thread?

What is the difference between implements Runnable or extends Thread?

1. Inheritance Option:   The limitation with "extends Thread" approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.  In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.

2. Reusability :  In "implements Runnable" , we are creating a different Runnable class for a specific behavior  job (if the work you want to be done is job). It gives us the freedom to reuse the specific
behavior job whenever required.
"extends Thread"  contains both thread and job specific behavior code. Hence once thread completes execution , it can not be restart again.   

3. Object Oriented Design:  Implementing Runnable should be preferred . It does not specializing or modifying the thread behavior . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a  relationship.
"extends Thread"  is not a good Object Oriented practice.

4. Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
"extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

5. Functions overhead :  "extends Thread"  means inheriting all the functions of the Thread class which we may do not need .  job can be done easily by Runnable without the Thread class functions overhead.

WHAT ARE THE 3 WAYS TO HANDLE THREADS SYNCHRONIZATION? ONE OF THEM WOULD BE THE WORD "SYNCHRONIZED" IN METHODS

1. Synchronized in method
2. Synchronized in instance block
3. Synchronized in static block

WHAT IS OOP(OBJECT ORIENTED PROGRAMMING)?

Programming paradigm based on objects that model human reality

EXPLAIN THE MOST IMPORTANT CHARACTERISTICS OF THE OBJECT ORIENTED PROGRAMMING?

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Composition
 

WHAT IS ENCAPSULATION, POLYMORPHISM?

Encapsulation is a method that enforce the access of a certain resource through a define way
Polymorphism is the ability of an object to behave as other objects (this can be done through inheritance)

WHAT IS INHERITANCE? DOES JAVA ALLOWS MULTIPLE INHERITANCE? HOW COULD YOU SIMULATE MULTIPLE INHERITANCE IN JAVA?

Inheritance is the ability to retrieve properties and functionalities of a parent class in order to make the code reusable
Java does not allow multiple inheritance since classes can only extend from one class
Multiple inheritance can be simulated wit the implementation of several interfaces

WHAT IS THE DIFFERENCE BETWEEN STATIC AND DYNAMIC POLYMORPHISM?

Static Polymorphism : Checked at compilation time is related to method overloading, compiler can undestand if a statement is correct due to the evaluation of the overloaded method
Dynamic Polymorphism : Checked at runtime is related to method overriding, the program can only evaluate the validity of the statement at runtime

WHAT IS THE DIFFERENCE BETWEEN AN ABSTRACT CLASS AND AN INTERFACE? 

Abstract class are those that have at least one abstract method (not defined method).
Interface is a java component that defines behavior, it has only abstract methods (not defined methods).What is ORM (Object relational mapping)?

WHAT IS ORM (OBJECT RELATIONAL MAPPING)?

 

Its a technique for converting data between incompatible type systems in object oriented programming languages. For example such technique can be applied to convert database data type into objects or viceversa

WHAT IS HIBERNATE? WHAT ARE THE ADVANTAGES? HOW DO YOU MANAGE TRANSACTIONS?

Hibernate : Is a tool or system that provides ORM with databases and several programming languages including java

Advantages : Manage the transaction with the database much more easier and in a standard fashion through the programming language

How does hibernate manage transactions : Through sessions or units of work, in order to make an efficient use of the database and concurrency issues, Hibernates offers these alternatives :

Automatic Versioning
Detached Objects
Extended Session 

HIERARCHY IN HIBERNATE, HOW DO YOU MAP CLASS INHERITANCE IN HIBERNATE?

Table per class hierarchy
Table per subclass
Table per concrete class
Implicit polymorphism

WHAT IS A UNIT TEST? AND AN INTEGRATION TEST? DID YOU USE A FRAMEWORK? 

Unit test : Is a process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation.
Integration test : Is a process in which two or more modules are combined together and tested as a group, generarly it happens after unit testing and before validation testing.
Frameworks : JUnit and Mockito
 

WHAT IS JUNIT? WHAT DOES IT TEST?

Its an automated testing framework, provides a library useful to perform unit test with several options 

WHAT IS A MOCK TEST? WHAT IS MOCKING FOR?

It is a test based on mocks in order to automate the unit testing, isolating the input dependencies (encapsulating dependencies within a mock)

Mocks are useful to perform automated unitesting without caring about dependencies 

WHAT IS TDD?

It is a software development process that relies on the repetition of a very short development cycle, first the developer writes an automated test case, then produces de minumum amount of code to pass the testm and finally refactors the new code to acceptable standards.

WHAT IS BDD?

Behavior driven development, is a software development technique that extends the test driven development, and aims to specify certain step while making such a test (given, when, then)

Story: Returns go to stock

In order to keep track of stock
As a store owner
I want to add items back to stock when they're returned.

Scenario 1: Refunded items should be returned to stock
Given that a customer previously bought a black sweater from me
And I have three black sweaters in stock.
When he returns the black sweater for a refund
Then I should have four black sweaters in stock.

Scenario 2: Replaced items should be returned to stock
Given that a customer previously bought a blue garment from me
And I have two blue garments in stock
And three black garments in stock.
When he returns the blue garment for a replacement in black
Then I should have three blue garments in stock
And two black garments in stock. 

 

WHAT IS THE DIFFERENCE BETWEEN BDD AND TDD?

BDD is the extension of TDD, but it specifies certain steps while making such a test (given, when, then)

WHAT IS A STUB? WHAT IS A DYNAMIC STUB? WHAT IS A STUB USED FOR? 

STUB : It is a piece of code or a little program that simulates a much complex code or program not yet in use.

STUB ARE USEFUL FOR : test a given portion of a software

WHAT ARE THE WEB SERVICES?  

A software system designed to support interoperable machine to machine interaction over a network

WHAT KIND OF WEB SERVICES EXISTS? 

There are several kind of web services, but mostly are those that uses SOAP implementation and REST implementation

WHAT IMPLEMENTATIONS DO YOU KNOW? 

SOAP (Simple Object Access Protocol) and REST (Representational State Transfer)

HAVE YOU WORK WITH ANY FRAMEWORK?

CXF is the framework that has been used in Hewlett Packard to handle web services intercomunication

WHAT IS THE DIFFERENCE BETWEEN SOAP AND REST?

The comunication protocol :

    SOAP (Simple Object Access Protocol) is an xml based protocol using a xml descriptor document called wsdl (web service descriptio language)

    REST (Representational State Transfer) is an architectural style that specifies constraints, when applied to web protocols like HTTP it uses certain methods (GET, POST, PUT, DELETE, PATCH) to interact with resources

The comunication format :

    SOAP is based in xml format

    REST is based on JSON format

WHAT ARE THE KNOWN FRAMEWORKS FOR SOAP AND REST?

So far I know CXF framework to work with web services

WHAT IS THE DIFFERENCE BETWEEN STATELESS, STATEFUL?

Stataless is a communication that do not preserve the state of the communication.

Stateful is a communication that do preserve the state of the communication.

Stateless means the state of the service don't persist between subsequent requests and response. 
whereas, in stateful the state is persisted between subsequent requests 
i.e. each request need to know and retain changes made in previous requests.

WHAT IS THE WSDL?

It is a xml document that describes a web services (usually seen as a contract)

WHAT WS HAS SECURITY? HOW DO YOU IMPLEMENT IT?

Confidentiality

    SSL Secure Socket Layer
    XML encryption standard

Authentication

    HTTP support Basic and Digest authentication
    SOAP Digital signature (SOAP DSIG) leverages public key cryptography
    OASIS (Organization for the Advancement of Structured Information Standards) is working on the Security Assertion Markup Language (SAML)    

Network Security
    
    This side is about securing comunication through internet considering network devices, not yet security implementation on this arean
 

WHAT IS A JSON FILE? WHAT IS AN XML? WHAT ARE THE DIFFERENCES?

JSON : Java Script Object Notation, light document (compared against xml) with a human easy to understand format that represents data 

XML : Extended Markup Language, it is an xml format based document that contains data within a tag structure 

What is the dependency injection (DI)?

What is Inversion of Control (IoC)?

What is the difference between DI and IoC?

What frameworks do you know that uses IoC?

Have you work with AOP?

What is Spring? What is its purpose? What are the advantages?

How can you configure Spring Core? Describe by Annotation and XML. How do you define beans in each?

How do you handle transactions with Spring and Hibernate? Describe by Annotation and XML

How can you define a list in Spring?

What is Spring MVC? What are the advantages?

Spring MVC using annotations or via context?

What is a software pattern? 

Describe the types of Patterns: Analisis, Design, Structure, Creation, Behaviour

Describe 3 design patterns of the presentation business and persistence layer. Give examples

What is a DTO? Is it a Pattern? When should I use it?

What kind of patterns do you know? How can you divide them?

What is the MVC pattern for?