Search This Blog

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

Thursday 23 February 2017

JSP Implicit Objects

JSP Implicit Objects

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without declaring them explicitly. These objects are created by JSP Engine during translation phase (while translating JSP to Servlet). They are being created inside service method so the developer can directly use them within Scriptlet without initializing and declaring them.

There are total 8+1 implicit objects available in JSP.

The request Object
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
The response Object:
The response object is an instance of a javax.servlet.http.HttpServletResponse object. The server creates the response object to represent the response to the client.
The out Object:
The out object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
The JspWriter object contains most of the methods as the java.io.PrintWriter class.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.
The session object is used to track client session between client requests.
The application Object:
The application object is an instance of a javax.servlet.ServletContext.
Application object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
The config Object:
The config object is an instantiation of javax.servlet.ServletConfig.
The config object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
The pageContext Object:
The pageContext object is an instance of  javax.servlet.jsp.PageContext. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of pageContext object.
The page Object:
Page object is a reference to the current Servlet instance (Converted Servlet, generated during translation phase from a JSP page). We can simply use this in place of it.
The exception Object
Exception object is used in exception handling for displaying the error messages. This object is only available to the JSP pages, which has isErrorPage set to true.


JSP Implicit Objects
JSP Implicit Objects



Thursday 9 February 2017

Autowiring In Spring

It is possible to automatically let Spring framework resolve dependencies for the bean by inspecting contents of the BeanFactory. This is kown as Autowiring.  A BeanFactory is able to autowire relationships between collaborating beans.
The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans won't be autowired.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing. In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element.






Some advantages of autowiring:
  • It can reduce the volume of configuration required.
  • It can cause configuration to keep itself up to date as your objects evolve. For example, if you need to add an additional dependency to a class, that dependency can be satisfied automatically without the need to modify configuration.
Some disadvantages of autowiring:

  • Wiring information may not be available to tools that may generate documentation from a Spring application context.
  • Autowiring by type will only work when there is a single bean definition of the type specified by the setter method or constructor argument. You need to use explicit wiring if there is any potential ambiguity.
Autowiring In Spring
Autowiring In Spring

Monday 6 February 2017

Default Methods in Java 8

Default Methods in Java 8
With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.


When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.

Example of Default Method


public interface Account {
default void OpenAccount(){
      System.out.println("This is the Account Interface . . . .");
}
}



public class SavingAccount implements Account{
public void OpenSavingAccount(){
      System.out.println("This is the Saving Account Class . . . .");
}
}


public class Main {
public static void main(String[] args) {
      SavingAccount sa=new SavingAccount();
      sa.OpenAccount(); // Default method of interface is called
      sa.OpenSavingAccount();
}
}


Upon executing the Main class, we get the following output.
This is the Account Interface . . . .
This is the Saving Account Class . . . .

Default Methods and Multiple Inheritance
In case of multiple Inheritance, where both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.
interface InterfaceOne
{
      // Default method
      default void show()
      {
            System.out.println("Default InterfaceOne");
      }
}

interface InterfaceTwo
{
      // Default method
      default void show()
      {
            System.out.println("Default InterfaceTwo");
      }
}

public class MainClass implements InterfaceOne, InterfaceTwo
{
      // Overriding default show method
      public void show()
      {
            // use super keyword to call the show
            // method of InterfaceOne interface
            InterfaceOne.super.show();

            // use super keyword to call the show
            // method of InterfaceTwo interface
            InterfaceTwo.super.show();
      }

      public static void main(String args[])
      {
            MainClass d = new MainClass();
            d.show();
      }
}

Upon executing the MainClass, we get the following output.
Default InterfaceOne
Default InterfaceTwo


Important Points:
1.     Interfaces can have default methods with implementation from java 8 onwards.
2.     Interfaces can have static methods as well similar to static method of classes.
3.     Default methods were introduced to provide backward comparability for old interfaces so that they can have new methods without effecting existing code.


Friday 3 February 2017

Lambda expressions in Java 8

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection.
A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown.
o    AnonymousAnonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about!
o    FunctionFunction because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.
o    Passed aroundA lambda expression can be passed as argument to a method or stored in a variable.
o    ConciseYou don’t need to write a lot of boilerplate like you do for anonymous classes.

Lambdas technically let you do anything that you could do prior to Java 8. But you no longer have to write clumsy code using anonymous classes.
 The result is that your code will be clearer and more flexible. For example, using a lambda expression you can create a custom Comparator object in a more concise way.

Before:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};


After (with lambda expressions):
Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

Lambda Expression Syntax
Lambda expressions address the bulkiness of anonymous inner. A lambda expression is composed of three parts.
A lambda expression is composed of parameters, an arrow,
and a body.

Argument List
Arrow Token
Body
(int x, int y)
->
x + y
The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.
Take a look at these examples:
(int x, int y) -> x + y

() -> 42

(String s) -> { System.out.println(s); }
 
The first expression takes two integer arguments, named x and y, and uses the expression form to return x+y.
The second expression takes no arguments and uses the expression form to return an integer 42.
The third expression takes a string and uses the block form to print the string to the console, and returns nothing.
Lambda Examples
Runnable Lambda
public class RunnableTest {
  public static void main(String[] args) {
    System.out.println("=== RunnableTest ===");
       // Anonymous Runnable
    Runnable r1 = new Runnable(){
         @Override
      public void run(){
        System.out.println("Hello world one!");
      }
    };
   
    // Lambda Runnable
    Runnable r2 = () -> System.out.println("Hello world two!");
   
    // Run them
    r1.run();
    r2.run();
   
  }
}
Comparator Lambda
In Java, the Comparator class is used for sorting collections. In the following example, an ArrayList consisting of Person objects is sorted based on surName. The following are the fields included in the Person class.
public class Person {
private String givenName;
private String surName;
private int age;
private String eMail;
private String phone;
private String address;
}

The following code applies a Comparator by using an anonymous inner class and a couple lambda expressions.

public class ComparatorTest {
 public static void main(String[] args) {
  
    // Create List of Person
        List<Person> personList1 = null;
   
      // Sort with Inner Class
    Collections.sort(personList1, new Comparator<Person>(){
      public int compare(Person p1, Person p2){
        return p1.getSurName().compareTo(p2.getSurName());
      }
    });
   
    System.out.println("=== Sorted Asc SurName ===");
    for(Person p:personList1){
      System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Use Lambda instead
   
    // Print Asc
    System.out.println("=== Sorted Asc SurName ===");
    Collections.sort(personList1, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Print Desc
    System.out.println("=== Sorted Desc SurName ===");
    Collections.sort(personList1, (p1p2) -> p2.getSurName().compareTo(p1.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
  }
}