Monday, 6 October 2014

8 new features for Java 8

by Sitansu 

NOTE: Make sure to also check our detailed tutorial Java 8 Features – The ULTIMATE Guide.
Jdk 1.8 aka, Java 8 is launched today meaning that the General Availability release of it is out in the open and developers can switch from Early Release releases to a tested release for production use. But what does it means for you, the busy Java developer? Well, here are some points that I condensed to mark this release:

1.Lamda Expressions

I started with lambda expressions as this is probably the most sought after feature in the language after probably Generics/Annotations in Java 5.
Here’s the syntax:
1(argtype arg...) -> { return some expression.. probably using these arguments }
What it does is that it reduces the code where it is obvious, such as in an anonymous innerclass. (Swing action handlers just got sexy, yay!)
So, a thread can be changed as:
1Runnable oldRunner = new Runnable(){
2    public void run(){
3        System.out.println("I am running");
4    }
5};
6Runnable java8Runner = () ->{
7    System.out.println("I am running");
8};
Similar to Scala, type inference is also possible in Lambdas. Consider the following available example:
1Comparator c = (a, b) -> Integer.compare(a.length(), b.length());
Here, the types of a,b (In this case String, from the Comparator interface) are inferred as the compare method is implemented.
The symbol used to separate the block from arguments, -> is quite similar to => already used in Scala and if you are good at it, there is not much reason to switch as you will feel the way lambdas are implemented in java is inadequate(and verbose), but for a good ‘ol java programmer, this is the way to go.

2.Generic Type changes and improvements

Taking clues from Lambdas, generic collections can also infer the data types to be used to an extent. The methods for instance using a generic collection need not specify genric types. Hence, the following method
1SomeClass.method();
Can be called simply ignoring the type information:
1SomeClass.method();
The type can be inferred by the method signature, which is helpful in nested calls like
1myCollection.sort().removeUseless().beautify();

3. Stream Collection Types (java.util.stream)

A stream is a iterator that allows a single run over the collection it is called on. Along with Lambdas, this is another noteworthy feature to watch out for. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores.
Example:
1List guys = list.getStream.collect(Collectors.toList())
can also be implemented parallely as
1List guys = list.getStream.parallel().collect(Collectors.toList()
Another nice example that reduces the collection to a single item is by calling reduce algorithem.
1int sum = numberList.stream().reduce(0, (x, y) -> x+y);
or,
1int sum = numberList.stream().reduce(0, Integer::sum);

4. Functional Interfaces (java.util.function)

These interfaces contain some default methods which need not be implemented and can run directly from the interface. This helps with existing code – changing interfaces need not make all the classes implementing it implement new methods. This is similar to Traits in Scala and functional interfaces will be compatible with lambdas.

5. Nashorn – The Node.js on JVM

This is the javascript engine that enables us to run javascript to run on a  jvm. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly.

6. Date/Time changes (java.time)

http://download.java.net/jdk8/docs/api/java/time/package-summary.html
The Date/Time API is moved to java.time package and Joda time format is followed. Another goodie is that most classes are Threadsafe and immutable.

7. Type Annotations

Now annotations can be used to decorate generic types itself.
Eg:
1List<@Nullable String>
which is not desired always, but can prove to be useful in certain circumstances. Apart from decorating Generic types, it can also be used in constructors and casting.
1new @NonEmpty @Readonly List(myNonEmptyStringSet)
2new @Interned MyObject()
3
4myString = (@NonNull String) myObject;
Even the array objects can be annoted:
1@NotNull String[] arr;
The inclusion of RuntimeVisibleTypeAnnotations and RuntimeInvisibleTypeAnnotations attributes which cause the .class file to save the annotation information.

8.Other – (nice to have) Changes

Reflection api is slightly increased with the support of TypeName, GenericString, etc.
String.join() method is a welcome addition as a lot of self created utility classes are created instead. So, the following example
1String abc= String.join(" ", "Java", "8");
Will get evaluated as “Java 8″.
In the Collections package, the Comparator interface is revamped and methods like reversed, comparing and thenCOmparing have been added which allow easy customization of comparison over multiple fields. Other libraries like the Concurrency and NIO have also been updated but is nothing noteworthy for following up and is keeping with the changes in the api.
Overall, Java8 is well thought of and is making mainstream java concise and picking some good parts of Scala/Clojure for the improving its syntax and addressing much sought features.

Java: Multiple Inheritance in Java and Composition vs In...

Java: Multiple Inheritance in Java and Composition vs In...: Sometime back I wrote few posts about  inheritance ,  interface  and  composition  in java. In this post, we will look into multipl...

Wednesday, 1 October 2014

JSP Interview Questions and Answers



JSP Interview Questions and Answers

  1. What is JSP and why do we need it?

    JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. JSP is extension of Servlet technology to help developers create dynamic pages with HTML like syntax.
    We can create user views in servlet also but the code will become very ugly and error prone. Also most of the elements in web page is static, so JSP page is more suitable for web pages. We should avoid business logic in JSP pages and try to use it only for view purpose. JSP scripting elements can be used for writing java code in JSP pages but it’s best to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same functionalities.
    One more benefit of JSP is that most of the containers support hot deployment of JSP pages. Just make the required changes in the JSP page and replace the old page with the updated jsp page in deployment directory and container will load the new JSP page. We don’t need to compile our project code or restart server whereas if we make change in servlet code, we need to build the complete project again and deploy it. Although most of the containers now provide hot deployment support for applications but still it’s more work that JSP pages.
  2. What are the JSP lifecycle phases?

    If you will look into JSP page code, it looks like HTML and doesn’t look anything like java classes. Actually JSP container takes care of translating the JSP pages and create the servlet class that is used in web application. JSP lifecycle phases are:
    1. Translation – JSP container checks the JSP page code and parse it to generate the servlet source code. For example in Tomcat you will find generated servlet class files atTOMCAT/work/Catalina/localhost/WEBAPP/org/apache/jsp directory. If the JSP page name is home.jsp, usually the generated servlet class name is home_jsp and file name is home_jsp.java
    2. Compilation – JSP container compiles the jsp class source code and produce class file in this phase.
    3. Class Loading – Container loads the class into memory in this phase.
    4. Instantiation – Container invokes the no-args constructor of generated class to load it into memory and instantiate it.
    5. Initialization – Container invokes the init method of JSP class object and initializes the servlet config with init params configured in deployment descriptor. After this phase, JSP is ready to handle client requests. Usually from translation to initialization of JSP happens when first request for JSP comes but we can configure it to be loaded and initialized at the time of deployment like servlets using load-on-startup element.
    6. Request Processing – This is the longest lifecycle of JSP page and JSP page processes the client requests. The processing is multi-threaded and similar to servlets and for every request a new thread is spawned and ServletRequest and ServletResponse object is created and JSP service method is invoked.
    7. Destroy – This is the last phase of JSP lifecycle where JSP class is unloaded from memory. Usually it happens when application is undeployed or the server is shut down.
  3. What are JSP lifecycle methods?

    JSP lifecycle methods are:
    1. jspInit(): This method is declared in JspPage and it’s implemented by JSP container implementations. This method is called once in the JSP lifecycle to initialize it with config params configured in deployment descriptor. We can override this method using JSP declaration scripting element to initialize any resources that we want to use in JSP page.
    2. _jspService(): This is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. We should not try to override it using JSP declaration scripting element. This method is defined in HttpJspPage interface.
    3. jspDestroy(): This method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.
  4. Which JSP lifecycle methods can be overridden?

    We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should override jspInit() methods to create common resources that we would like to use in JSP service method and override jspDestroy() method to release the common resources.

Multiple Inheritance in Java and Composition vs Inheritance




Sometime back I wrote few posts about inheritanceinterface and composition in java. In this post, we will look into multiple inheritance and then learn about benefits of composition over inheritance.

Multiple Inheritance in Java

Multiple inheritance is the capability of creating a single class with multiple superclasses. Unlike some other popular object oriented programming languages like C++, java doesn’t provide support for multiple inheritance in classes. Java doesn’t support multiple inheritance in classes because it can lead to diamond problem and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritance.

Diamond Problem

To understand diamond problem easily, let’s assume that multiple inheritance was supported in java. In that case, we could have a class hierarchy like below image.
diamond-problem-multiple-inheritance
Let’s say SuperClass is an abstract class declaring some method and ClassA, ClassB are concrete classes.
SuperClass.java
1
2
3
4
5
6
package com.journaldev.inheritance;
public abstract class SuperClass {
    public abstract void doSomething();
}
ClassA.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.journaldev.inheritance;
public class ClassA extends SuperClass{
     
    @Override
    public void doSomething(){
        System.out.println("doSomething implementation of A");
    }
     
    //ClassA own method
    public void methodA(){
         
    }
}
ClassB.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.journaldev.inheritance;
public class ClassB extends SuperClass{
    @Override
    public void doSomething(){
        System.out.println("doSomething implementation of B");
    }
     
    //ClassB specific method
    public void methodB(){
         
    }
}
Now let’s say ClassC implementation is something like below and it’s extending both ClassA and ClassB.
ClassC.java
1
2
3
4
5
6
7
8
9
10
package com.journaldev.inheritance;
public class ClassC extends ClassA, ClassB{
    public void test(){
        //calling super class method
        doSomething();
    }
}
Notice that test() method is making a call to superclass doSomething() method, this leads to the ambiguity as compiler doesn’t know which superclass method to execute and because of the diamond shaped class diagram, it’s referred as Diamond Problem and this is the main reason java doesn’t support multiple inheritance in classes.
Notice that the above problem with multiple class inheritance can also come with only three classes where all of them has at least one common method.

Multiple Inheritance in Interfaces

You might have noticed that I am always saying that multiple inheritance is not supported in classes but it’s supported in interfaces and a single interface can extend multiple interfaces, below is a simple example.
InterfaceA.java
1
2
3
4
5
6
package com.journaldev.inheritance;
public interface InterfaceA {
    public void doSomething();
}
InterfaceB.java
1
2
3
4
5
6
package com.journaldev.inheritance;
public interface InterfaceB {
    public void doSomething();
}
Notice that both the interfaces are declaring same method, now we can have an interface extending both these interfaces like below.
InterfaceC.java
1
2
3
4
5
6
7
8
package com.journaldev.inheritance;
public interface InterfaceC extends InterfaceA, InterfaceB {
    //same method is declared in InterfaceA and InterfaceB both
    public void doSomething();
     
}
This is perfectly fine because the interfaces are only declaring the methods and the actual implementation will be done by concrete classes implementing the interfaces, so there is no possibility of any kind of ambiguity in multiple inheritance in interface.
Thats why a java class can implement multiple inheritance, something like below example.
InterfacesImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.journaldev.inheritance;
public class InterfacesImpl implements InterfaceA, InterfaceB, InterfaceC {
    @Override
    public void doSomething() {
        System.out.println("doSomething implementation of concrete class");
    }
    public static void main(String[] args) {
        InterfaceA objA = new InterfacesImpl();
        InterfaceB objB = new InterfacesImpl();
        InterfaceC objC = new InterfacesImpl();
         
        //all the method calls below are going to same concrete implementation
        objA.doSomething();
        objB.doSomething();
        objC.doSomething();
    }
}
Did you noticed that every time I am overriding any superclass method or implementing any interface method, I am using @Override annotation, it’s one of the three built-in java annotations and we shouldalways use override annotation when overriding any method.

Composition for the rescue

So what to do if we want to utilize ClassA function methodA() and ClassB function methodB() in ClassC, the solution lies in using composition, here is a refactored version of ClassC that is using composition to utilize both classes methods and also using doSomething() method from one of the objects.
ClassC.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.journaldev.inheritance;
public class ClassC{
    ClassA objA = new ClassA();
    ClassB objB = new ClassB();
     
    public void test(){
        objA.doSomething();
    }
     
    public void methodA(){
        objA.methodA();
    }
     
    public void methodB(){
        objB.methodB();
    }
}

Composition vs Inheritance

One of the best practices of java programming is to “favor composition over inheritance”, we will look into some of the aspects favoring this approach.
  1. Suppose we have a superclass and subclass as follows:
    ClassC.java
    1
    2
    3
    4
    5
    6
    7
    package com.journaldev.inheritance;
    public class ClassC{
        public void methodC(){
        }
    }
    ClassD.java
    1
    2
    3
    4
    5
    6
    7
    8
    package com.journaldev.inheritance;
    public class ClassD extends ClassC{
        public int test(){
            return 0;
        }
    }
    The above code compiles and works fine but what if ClassC implementation is changed like below:
    ClassC.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    package com.journaldev.inheritance;
    public class ClassC{
        public void methodC(){
        }
        public void test(){
        }
    }
    Notice that test() method already exists in the subclass but the return type is different, now the ClassD won’t compile and if you are using any IDE, it will suggest you to change the return type in either superclass or subclass.
    Now imagine the situation where we have multiple level of class inheritance and superclass is not controlled by us, we will have no choice but to change our subclass method signature or it’s name to remove the compilation error, also we will have to make change in all the places where our subclass method was getting invoked, so inheritance makes our code fragile.
    The above problem will never occur with composition and that makes it more favorable over inheritance.
  2. Another problem with inheritance is that we are exposing all the superclass methods to the client and if our superclass is not properly designed and there are security holes, then even though we take complete care in implementing our class, we get affected by the poor implementation of superclass.
    Composition helps us in providing controlled access to the superclass methods whereas inheritance doesn’t provide any control of the superclass methods, this is also one of the major advantage of composition over inheritance.
  3. Another benefit with composition is that it provides flexibility in invocation of methods. Our above implementation of ClassC is not optimal and provides compile time binding with the method that will be invoked, with minimal change we can make the method invocation flexible and make it dynamic.
    ClassC.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package com.journaldev.inheritance;
    public class ClassC{
        SuperClass obj = null;
        public ClassC(SuperClass o){
            this.obj = o;
        }
        public void test(){
            obj.doSomething();
        }
         
        public static void main(String args[]){
            ClassC obj1 = new ClassC(new ClassA());
            ClassC obj2 = new ClassC(new ClassB());
             
            obj1.test();
            obj2.test();
        }
    }
    Output of above program is:
    1
    2
    doSomething implementation of A
    doSomething implementation of B
    This flexibility in method invocation is not available in inheritance and boosts the best practice to favor composition over inheritance.
  4. Unit testing is easy in composition because we know what all methods we are using from superclass and we can mock it up for testing whereas in inheritance we depend heavily on superclass and don’t know what all methods of superclass will be used, so we need to test all the methods of superclass, that is an extra work and we need to do it unnecessarily because of inheritance.