Monday, December 26, 2016

Java Interview Questions TechM

1) how to remove duplicates in an ArrayList?
Ans:
You can create a LinkedHashSet from the list. The LinkedHashSet will contain each element only once, and in the same order as the List.
list = new ArrayList<String>(new LinkedHashSet<String>(list))
example:
       ArrayList ss = new ArrayList<>();
ss.add("a");
       ss.add("t");
       ss.add("d");
       ss.add("i");
       ss.add("s");
       ss.add("a");
       System.out.println(ss);
       ArrayList ss2 = new ArrayList<>(new LinkedHashSet(ss));
       System.out.println(ss2);

2) why do we override hashCode() method.
Ans:
"If two objects are equal using Object class equals method, then thehashcode method should give the same value for these two objects." So, if in our class we override equals we should override hashcode method also to fallow this rule.

3) write a thread safe singleton?
Ans:
public class Dev21Singleton {

            private static Dev21Singleton instance = null;

            protected Dev21Singleton() {
            }

            // Lazy Initialization (If required then only)
            public static Dev21Singleton getInstance() {
                        if (instance == null) {
                                    // Thread Safe. Might be costly operation in some case
                                    synchronized (Dev21Singleton.class) {
                                                if (instance == null) {
                                                            instance = new Dev21Singleton();
                                                }
                                    }
                        }
                        return instance;
            }
}

4) Questions about abstract class constructor, private variables in abstract class etc.

5) why can’t we create instance of an abstract class? what stops us? have you ever tried
   creating one?

Ans:
It's because an abstract class isn't complete. One or more parts of its public interface are not implemented. You've said what they're going to be - what they're called, what their name is, what they return - but no implementation has been provided, so nobody would be able to call them.
Compilers prevent you from instantiating such incomplete objects on the basis that if you do instantiate an object you're going to want to use its entire public interface (this assumption is related to the idea that an object should do a minimal set of things, so that the public interface is not too large to manage). It's also a useful safety net. The compiler says "hang on, this is just part of a class, you need to provide the rest of it".

6) MVC questions -- like how to pass textbox val back to controller etc etc.

7) data annotation, 1 to many relationship in entity framework, primary and composite key in entity framework.

Apache Ant Build Tool

Preparing the project

We want to separate the source from the generated files, so our java source files will be in src folder. All generated files should be under build, and there splitted into several subdirectories for the individual steps: classes for our compiled files and jar for our own JAR-file.
We have to create only the src directory. (Because I am working on Windows, here is the win-syntax - translate to your shell):
md src
The following simple Java class just prints a fixed message out to STDOUT, so just write this code into src\oata\HelloWorld.java.
package oata;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
Now just try to compile and run that:
md build\classes
javac -sourcepath src -d build\classes src\oata\HelloWorld.java
java -cp build\classes oata.HelloWorld
which will result in
Hello World

Creating a jar-file is not very difficult. But creating a startable jar-file needs more steps: create a manifest-file containing the start class, creating the target directory and archiving the files.
echo Main-Class: oata.HelloWorld>myManifest
md build\jar
jar cfm build\jar\HelloWorld.jar myManifest -C build\classes .
java -jar build\jar\HelloWorld.jar
Note: Do not have blanks around the >-sign in the echo Main-Class instruction because it would falsify it!

Four steps to a running application

After finishing the java-only step we have to think about our build process. We have to compile our code, otherwise we couldn't start the program. Oh - "start" - yes, we could provide a target for that. We should package our application. Now it's only one class - but if you want to provide a download, no one would download several hundreds files ... (think about a complex Swing GUI - so let us create a jar file. A startable jar file would be nice ... And it's a good practise to have a "clean" target, which deletes all the generated stuff. Many failures could be solved just by a "clean build".
By default Ant uses build.xml as the name for a buildfile, so our .\build.xml would be:
<project>

    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="oata.HelloWorld"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="build/jar/HelloWorld.jar" fork="true"/>
    </target>

</project>
Now you can compile, package and run the application via
ant compile
ant jar
ant run
Or shorter with
ant compile jar run
While having a look at the buildfile, we will see some similar steps between Ant and the java-only commands:
java-onlyAnt
md build\classes
javac
    -sourcepath src
    -d build\classes
    src\oata\HelloWorld.java
echo Main-Class: oata.HelloWorld>mf
md build\jar
jar cfm
    build\jar\HelloWorld.jar
    mf
    -C build\classes
    .



java -jar build\jar\HelloWorld.jar
  
<mkdir dir="build/classes"/>
<javac
    srcdir="src"
    destdir="build/classes"/>
<!-- automatically detected -->
<!-- obsolete; done via manifest tag -->
<mkdir dir="build/jar"/>
<jar
    destfile="build/jar/HelloWorld.jar"

    basedir="build/classes">
    <manifest>
        <attribute name="Main-Class" value="oata.HelloWorld"/>
    </manifest>
</jar>
<java jar="build/jar/HelloWorld.jar" fork="true"/>
  

Enhance the build file

Now we have a working buildfile we could do some enhancements: many time you are referencing the same directories, main-class and jar-name are hard coded, and while invocation you have to remember the right order of build steps.
The first and second point would be addressed with properties, the third with a special property - an attribute of the <project>-tag and the fourth problem can be solved using dependencies.
<project name="HelloWorld" basedir="." default="main">

    <property name="src.dir"     value="src"/>

    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>

    <property name="main-class"  value="oata.HelloWorld"/>



    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
    </target>

    <target name="clean-build" depends="clean,jar"/>

    <target name="main" depends="clean,run"/>

</project>
Now it's easier, just do a ant and you will get
Buildfile: build.xml

clean:

compile:
    [mkdir] Created dir: C:\...\build\classes
    [javac] Compiling 1 source file to C:\...\build\classes

jar:
    [mkdir] Created dir: C:\...\build\jar
      [jar] Building jar: C:\...\build\jar\HelloWorld.jar

run:
     [java] Hello World

main:

BUILD SUCCESSFUL

Using external libraries

Somehow told us not to use syso-statements. For log-Statements we should use a Logging-API - customizable on a high degree (including switching off during usual life (= not development) execution). We use Log4J for that, because
  • it is not part of the JDK (1.4+) and we want to show how to use external libs
  • it can run under JDK 1.2 (as Ant)
  • it's highly configurable
  • it's from Apache ;-)

We store our external libraries in a new directory lib. Log4J can be downloaded [1] from Logging's Homepage. Create the lib directory and extract the log4j-1.2.9.jar into that lib-directory. After that we have to modify our java source to use that library and our buildfile so that this library could be accessed during compilation and run.
Working with Log4J is documented inside its manual. Here we use the MyApp-example from the Short Manual [2]. First we have to modify the java source to use the logging framework:
package oata;

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class HelloWorld {
    static Logger logger = Logger.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();
        logger.info("Hello World");          // the old SysO-statement
    }
}
Most of the modifications are "framework overhead" which has to be done once. The blue line is our "old System-out" statement.
Don't try to run ant - you will only get lot of compiler errors. Log4J is not inside the classpath so we have to do a little work here. But do not change the CLASSPATH environment variable! This is only for this project and maybe you would break other environments (this is one of the most famous mistakes when working with Ant). We introduce Log4J (or to be more precise: all libraries (jar-files) which are somewhere under .\lib) into our buildfile:
<project name="HelloWorld" basedir="." default="main">
    ...
    <property name="lib.dir"     value="lib"/>

    <path id="classpath">
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

    ...

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
    </target>

    <target name="run" depends="jar">
        <java fork="true" classname="${main-class}">
            <classpath>
                <path refid="classpath"/>
                <path location="${jar.dir}/${ant.project.name}.jar"/>
            </classpath>
        </java>
    </target>

    ...

</project>
In this example we start our application not via its Main-Class manifest-attribute, because we could not provide a jarname and a classpath. So add our class in the red line to the already defined path and start as usual. Running ant would give (after the usual compile stuff):
[java] 0 [main] INFO oata.HelloWorld  - Hello World
What's that?
  • [java] Ant task running at the moment
  • 0 sorry don't know - some Log4J stuff
  • [main] the running thread from our application
  • INFO log level of that statement
  • oata.HelloWorld source of that statement
  • - separator
  • Hello World the message
For another layout ... have a look inside Log4J's documentation about using other PatternLayout's.

Configuration files

Why we have used Log4J? "It's highly configurable"? No - all is hard coded! But that is not the debt of Log4J - it's ours. We had coded BasicConfigurator.configure(); which implies a simple, but hard coded configuration. More comfortable would be using a property file. In the java source delete the BasicConfiguration-line from the main() method (and the related import-statement). Log4J will search then for a configuration as described in it's manual. Then create a new file src/log4j.properties. That's the default name for Log4J's configuration and using that name would make life easier - not only the framework knows what is inside, you too!
log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n
This configuration creates an output channel ("Appender") to console named as stdout which prints the message (%m) followed by a line feed (%n) - same as the earlier System.out.println() :-) Oooh kay - but we haven't finished yet. We should deliver the configuration file, too. So we change the buildfile:
    ...
    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
        <copy todir="${classes.dir}">
            <fileset dir="${src.dir}" excludes="**/*.java"/>
        </copy>
    </target>
    ...
This copies all resources (as long as they haven't the suffix ".java") to the build directory, so we could start the application from that directory and these files will included into the jar.

Testing the class

In this step we will introduce the usage of the JUnit [3] testframework in combination with Ant. Because Ant has a built-in JUnit 3.8.2 you could start directly using it. Write a test class in src\HelloWorldTest.java:
public class HelloWorldTest extends junit.framework.TestCase {

    public void testNothing() {
    }
    
    public void testWillAlwaysFail() {
        fail("An error message");
    }
    
}
Because we dont have real business logic to test, this test class is very small: just show how to start. For further information see the JUnit documentation [3] and the manual of junit task. Now we add a junit instruction to our buildfile:
    ...

    <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>

    <target name="run" depends="jar">
        <java fork="true" classname="${main-class}">
            <classpath>
                <path refid="classpath"/>
                <path refid="application"/>
            </classpath>
        </java>
    </target>
    
    <target name="junit" depends="jar">
        <junit printsummary="yes">
            <classpath>
                <path refid="classpath"/>
                <path refid="application"/>
            </classpath>
            
            <batchtest fork="yes">
                <fileset dir="${src.dir}" includes="*Test.java"/>
            </batchtest>
        </junit>
    </target>

    ...

We reuse the path to our own jar file as defined in run-target by giving it an ID and making it globally available. The printsummary=yes lets us see more detailed information than just a "FAILED" or "PASSED" message. How much tests failed? Some errors? Printsummary lets us know. The classpath is set up to find our classes. To run tests the batchtest here is used, so you could easily add more test classes in the future just by naming them *Test.java. This is a common naming scheme.
After a ant junit you'll get:
...
junit:
    [junit] Running HelloWorldTest
    [junit] Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 0,01 sec
    [junit] Test HelloWorldTest FAILED

BUILD SUCCESSFUL
...
We can also produce a report. Something that you (and other) could read after closing the shell .... There are two steps: 1. let <junit> log the information and 2. convert these to something readable (browsable).

    ...
    <property name="report.dir"  value="${build.dir}/junitreport"/>
    ...
    <target name="junit" depends="jar">
        <mkdir dir="${report.dir}"/>
        <junit printsummary="yes">
            <classpath>
                <path refid="classpath"/>
                <path refid="application"/>
            </classpath>
            
            <formatter type="xml"/>
            
            <batchtest fork="yes" todir="${report.dir}">
                <fileset dir="${src.dir}" includes="*Test.java"/>
            </batchtest>
        </junit>
    </target>
    
    <target name="junitreport">
        <junitreport todir="${report.dir}">
            <fileset dir="${report.dir}" includes="TEST-*.xml"/>
            <report todir="${report.dir}"/>
        </junitreport>
    </target>

Because we would produce a lot of files and these files would be written to the current directory by default, we define a report directory, create it before running the junit and redirect the logging to it. The log format is XML so junitreport could parse it. In a second target junitreport should create a browsable HTML-report for all generated xml-log files in the report directory. Now you can open the ${report.dir}\index.html and see the result (looks something like JavaDoc).
Personally I use two different targets for junit and junitreport. Generating the HTML report needs some time and you dont need the HTML report just for testing, e.g. if you are fixing an error or a integration server is doing a job.

Java Latest Interview Questions

   1) Factory Pattern Example:
                                                Shape
                Circle                     Rectangle            Triangle
package others;
interface Shape {
       public void draw();
}

class Circle implements Shape {
       public void draw() {
              System.out.println("circle..");
       }
}

class Triangle implements Shape {
       public void draw() {
              System.out.println("tringle..");
       }
}

class Rectangle implements Shape {
       public void draw() {
              System.out.println("Rectangle..");
       }
}

class ShapeFactory
{
       public Shape getShape(String type)
       {
              if(type == null)
                     return null;
              if(type.equalsIgnoreCase("circle"))
                     return new Circle();
              if(type.equalsIgnoreCase("rectangle"))
                     return new Rectangle();
              if(type.equalsIgnoreCase("Triangle"))
                     return new Triangle();
              else
                           return null;
             
       }
}

public class FactoryImpl {

       public static void main(String s[])
       {
              ShapeFactory sf = new ShapeFactory();
              Shape s1 = sf.getShape("circle");
              s1.draw();
              Shape s2 = sf.getShape("triangle");
              s2.draw();
              Shape s3 = sf.getShape("rectangle");
              s3.draw();
              Shape s4 = sf.getShape(null);
              s4.draw();
             
       }
      
}

2)      Function overriding rules:
1)      If we are overriding a method, and making object of child class and assign it in parent ref variable, then the method call will always execute method of child (or we can say method of class for which object is created). If the method does not exist in child them it will execute the class of parent.
2)      We cannot reduce the visibility of overridden method, means a public method cannot be overridden as private or protected.
3)      We cannot override private methods; if we do so then it will automatically make it as local method, so no override.
4)      If we put throws in parent method then, we are allowed to omit it in child overridden method.
5)      If we put throws in parent method and in child method also, then child throwing exception will always be lower than parent one for example if parent is IOException then we cannot put Exception in child class.
package others;

import java.io.IOException;
import java.util.HashSet;

class A {
       public  void printTest(int i) throws IOException {
              System.out.println("A");
       }
}

public class OverrideTest extends A {
       @Override
       public  void printTest(int j)  {
              System.out.println("B");
       }

       public static void main(String s[]) {
              OverrideTest a = new OverrideTest();

                     a.printTest(10);
}
4) What is class loader?
The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.[1] Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of classloaders. Delegation is an important concept to understand when learning about classloaders.
Java ClassLoader loads a java class file into java virtual machine. It is as simple as that. It is not a huge complicated concept to learn and every java developer must know about the java class loaders and how it works.

Types (Hierarchy) of Java Class Loaders

Java class loaders can be broadly classified into below categories:
  • Bootstrap Class Loader
    Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader
    JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
  • System Class Loader
    Java classes that are available in the java classpath are loaded using System class loader.
You can see more class loaders like java.net.URLClassLoader, java.security.SecureClassLoader etc. Those are all extended from java.lang.ClassLoader
10) String s = “a^b^c~1^2^3~k^l^m……”;
Print above result in following format:
a              b             c
1              2              3
K             l               m
Answer:
package others;

public class StringPattern {
       public static void main(String s[])
       {
             
              String str = "a^b^c~1^2^3~k^l^m~5^6^7";
             
              for(int i=0;i<str.length();i++)
              {
                     if(str.charAt(i) == '^')
                     {
                           System.out.print(str.charAt(i-1) + " ");
                     }
                     if(str.charAt(i) == '~')
                     {
                           System.out.print(str.charAt(i-1) + " ");
                           System.out.println();
                     }
                     if(i==str.length()-1)
                     {
                           System.out.print(str.charAt(i) + " ");
                     }
                    
              }
       }
      
}

7) System.out.println() – is it overloaded – go inside to check.
Ans: yes it is overloaded, println() function further calls println().
6) how json is internally formed from a class object in restful webservice.
@RequestMapping(value="/getuserrole",method = RequestMethod.GET)
public @ResponseBody
Map<String,Map<String,List<String>>> getUserRoleList(@RequestParam("sso") String sso) {
List<String> lstAvailableRoles = new ArrayList<String>();
List<String> lstAssignedRoles = new ArrayList<String>();
Map<String,List<String>> mpRoles = new HashMap<String,List<String>>();
Map<String,Map<String,List<String>>> result = new HashMap<String,Map<String,List<String>>>();

lstAvailableRoles = usrRoleService.getAvailableRoleList(sso);
lstAssignedRoles = usrRoleService.getAssignedRoleList(sso);
mpRoles.put(AppConstant.AVAILABLE_ROLE, lstAvailableRoles);
mpRoles.put(AppConstant.ASSIGNED_ROLE, lstAssignedRoles);
result.put(AppConstant.RESULTS,mpRoles);
return result;
}
9) how annotation works internally.
Ans:
The first main distinction between kinds of annotation is whether they're used at compile time and then discarded (like @Override) or placed in the compiled class file and available at runtime (like Spring's @Component). This is determined by the @Retention policy of the annotation. If you're writing your own annotation, you'd need to decide whether the annotation is helpful at runtime (for autoconfiguration, perhaps) or only at compile time (for checking or code generation).
When compiling code with annotations, the compiler sees the annotation just like it sees other modifiers on source elements, like access modifiers (public/private) or final. When it encounters an annotation, it runs an annotation processor, which is like a plug-in class that says it's interested a specific annotation. The annotation processor generally uses the Reflection API to inspect the elements being compiled and may simply run checks on them, modify them, or generate new code to be compiled. @Override is an example of the first; it uses the Reflection API to make sure it can find a match for the method signature in one of the superclasses and uses the Messagerto cause a compile error if it can't.
There are a number of tutorials available on writing annotation processors; here's a useful one. Look through the methods on the Processor interface for how the compiler invokes an annotation processor; the main operation takes place in the process method, which gets called every time the compiler sees an element that has a matching annotation.
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
    String author() default "Pankaj";
    String date();
    int revision() default 1;
    String comments();
}
·         Annotation methods can’t have parameters.
·         Annotation methods return types are limited to primitives, String, Enums, Annotation or array of these.
·         Annotation methods can have default values.
·         Annotations can have meta annotations attached to them. Meta annotations are used to provide information about the annotation. There are four types of meta annotations:
1.      @Documented – indicates that elements using this annotation should be documented by javadoc and similar tools. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.
2.      @Target – indicates the kinds of program element to which an annotation type is applicable. Some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target meta-annotation is not present, then annotation can be used on any program element.
3.      @Inherited – indicates that an annotation type is automatically inherited. If user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached.
4.      @Retention – indicates how long annotations with the annotated type are to be retained. It takes RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

Java Built-in Annotations

Java Provides three built-in annotations.
1.      @Override – When we want to override a method of Superclass, we should use this annotation to inform compiler that we are overriding a method. So when superclass method is removed or changed, compiler will show error message. Learn why we should always use java override annotation while overriding a method.
2.      @Deprecated – when we want the compiler to know that a method is deprecated, we should use this annotation. Java recommends that in javadoc, we should provide information for why this method is deprecated and what is the alternative to use.
3.      @SuppressWarnings – This is just to tell compiler to ignore specific warnings they produce, for example using raw types in java generics. It’s retention policy is SOURCE and it gets discarded by compiler.

Calling above defined custom annotation – MethodInfo
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class AnnotationExample {

    public static void main(String[] args) {
    }

    @Override
    @MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)
    public String toString() {
        return "Overriden toString method";
    }

    @Deprecated
    @MethodInfo(comments = "deprecated method", date = "Nov 17 2012")
    public static void oldMethod() {
        System.out.println("old method, don't use it.");
    }

    @SuppressWarnings({ "unchecked", "deprecation" })
    @MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)
    public static void genericsTest() throws FileNotFoundException {
        List l = new ArrayList();
        l.add("abc");
        oldMethod();
    }

}

Parsing above annotation defined:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationParsing {

    public static void main(String[] args) {
        try {
            for (Method method : AnnotationParsing.class
                    .getClassLoader()
                    .loadClass(("com.journaldev.annotations.AnnotationExample"))
                    .getMethods()) {
                // checks if MethodInfo annotation is present for the method
                if (method
                        .isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {
                    try {
                        // iterates all the annotations available in the method
                        for (Annotation anno : method.getDeclaredAnnotations()) {
                            System.out.println("Annotation in Method '"
                                    + method + "' : " + anno);
                        }
                        MethodInfo methodAnno = method
                                .getAnnotation(MethodInfo.class);
                        if (methodAnno.revision() == 1) {
                            System.out.println("Method with revision no 1 = "
                                    + method);
                        }

                    } catch (Throwable ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } catch (SecurityException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

19) what is JMS:
Ans:
JMS Tutorial
JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It provides loosely coupled, reliable and asynchronous communication.

Requirement of JMS

Generally, user sends message to application. But, if we want to send message from one application to another, we need to use JMS API.
Consider a scenario, one application A is running in INDIA and another application B is running in USA. To send message from A application to B, we need to use JMS.

Advantage of JMS

1) Asynchronous: To receive the message, client is not required to send request. Message will arrive automatically to the client.
2) Reliable: It provides assurance that message is delivered.

1) Point-to-Point (PTP) Messaging Domain

In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message oriented middleware (MOM).
The Queue is responsible to hold the message until receiver is ready.
In PTP model, there is no timing dependency between sender and receiver.
jms point to point model

2) Publisher/Subscriber (Pub/Sub) Messaging Domain

In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting. Here, Topic is used as a message oriented middleware that is responsible to hold and deliver messages.
In PTP model, there is timing dependency between publisher and subscriber.
jms point to point model

JMS Programming Model

jms programming model

JMS Queue Example

To develop JMS queue example, you need to install any application server. Here, we are using glassfish3 server where we are creating two JNDI.
  1. Create connection factory named myQueueConnectionFactory
  2. Create destination resource named myQueue
After creating JNDI, create server and receiver application. You need to run server and receiver in different console. Here, we are using eclipse IDE, it is opened in different console by default.

1) Create connection factory and destination resource

Open server admin console by the URL http://localhost:4848
Login with the username and password.
Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the Resource Type as QueueConnectionFactory then click on ok button.
jms queue connection factory
Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical destination name then click on ok button.
jms queue destination resource

2) Create sender and receiver application

Let's see the Sender and Receiver code. Note that Receiver is attached with listener which will be invoked when user sends message.
File: MySender.java
1.    import java.io.BufferedReader;  
2.    import java.io.InputStreamReader;  
3.    import javax.naming.*;  
4.    import javax.jms.*;  
5.      
6.    public class MySender {  
7.        public static void main(String[] args) {  
8.            try  
9.            {   //Create and start connection  
10.             InitialContext ctx=new InitialContext();  
11.             QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");  
12.             QueueConnection con=f.createQueueConnection();  
13.             con.start();  
14.             //2) create queue session  
15.             QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  
16.             //3) get the Queue object  
17.             Queue t=(Queue)ctx.lookup("myQueue");  
18.             //4)create QueueSender object         
19.             QueueSender sender=ses.createSender(t);  
20.             //5) create TextMessage object  
21.             TextMessage msg=ses.createTextMessage();  
22.               
23.             //6) write message  
24.             BufferedReader b=new BufferedReader(new InputStreamReader(System.in));  
25.             while(true)  
26.             {  
27.                 System.out.println("Enter Msg, end to terminate:");  
28.                 String s=b.readLine();  
29.                 if (s.equals("end"))  
30.                     break;  
31.                 msg.setText(s);  
32.                 //7) send message  
33.                 sender.send(msg);  
34.                 System.out.println("Message successfully sent.");  
35.             }  
36.             //8) connection close  
37.             con.close();  
38.         }catch(Exception e){System.out.println(e);}  
39.     }  
40. }  
File: MyReceiver.java
1.    import javax.jms.*;  
2.    import javax.naming.InitialContext;  
3.      
4.    public class MyReceiver {  
5.        public static void main(String[] args) {  
6.            try{  
7.                //1) Create and start connection  
8.                InitialContext ctx=new InitialContext();  
9.                QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");  
10.             QueueConnection con=f.createQueueConnection();  
11.             con.start();  
12.             //2) create Queue session  
13.             QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  
14.             //3) get the Queue object  
15.             Queue t=(Queue)ctx.lookup("myQueue");  
16.             //4)create QueueReceiver  
17.             QueueReceiver receiver=ses.createReceiver(t);  
18.               
19.             //5) create listener object  
20.             MyListener listener=new MyListener();  
21.               
22.             //6) register the listener object with receiver  
23.             receiver.setMessageListener(listener);  
24.               
25.             System.out.println("Receiver1 is ready, waiting for messages...");  
26.             System.out.println("press Ctrl+c to shutdown...");  
27.             while(true){                  
28.                 Thread.sleep(1000);  
29.             }  
30.         }catch(Exception e){System.out.println(e);}  
31.     }  
32.   
33. }  

File: MyListener.java
1.    import javax.jms.*;  
2.    public class MyListener implements MessageListener {  
3.      
4.        public void onMessage(Message m) {  
5.            try{  
6.            TextMessage msg=(TextMessage)m;  
7.          
8.            System.out.println("following message is received:"+msg.getText());  
9.            }catch(JMSException e){System.out.println(e);}  
10.     }  
11. }  




Printed till here





















11) read a file and count number of words start from vowel.
Ans:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadVowelFromFile {

       public static void main(String...s)
       {

              BufferedReader br = null;
              int counter = 0;
              try {
                     br = new BufferedReader(new FileReader("e:\\vowel.txt"));
                     String currLine = null;
                     while((currLine = br.readLine())!=null)
                     {
                           System.out.println(currLine);
                           String t[] = currLine.split(" ");
                           for(String c:t)
                           {
                                  if(c.toLowerCase().charAt(0) == 'a' || c.toLowerCase().charAt(0) == 'e' || c.toLowerCase().charAt(0) == 'i' || c.toLowerCase().charAt(0) == 'o' || c.toLowerCase().charAt(0) == 'u')
                                  {
                                         counter++;
                                  }
                           }
                     }
                     System.out.println("Vowels: " + counter);
                    
              } catch (FileNotFoundException e) {
                     e.printStackTrace();
              }
              catch (IOException e) {
                     e.printStackTrace();
              }
              finally{
                     if(br!=null)
                           try {
                                  br.close();
                           } catch (IOException e) {
                                  e.printStackTrace();
                           }
              }
             
       }
}

10) explaination of inner join, left and right join.
Ans:
create table stock (stock_id number(10) primary key not null, stock_code varchar2(20), stock_name varchar2(50));
create table stock_detail ( stock_id number(10), comp_name varchar2(20), comp_desc varchar2(1000), FOREIGN KEY (stock_id) REFERENCES stock(stock_id));

insert into stock values(101,'A','AOAO');
insert into stock values(102,'B','BOBO');
insert into stock values(103,'C','COCO');
insert into stock values(104,'D','DODO');
insert into stock values(105,'E','EOEO');

insert into stock_detail values(101,'BSL','noida sec 62');
insert into stock_detail values(102,'IBM','noida sec 64');
insert into stock_detail values(106,'IBM','noida sec 64');

inner join:
select * from stock s, stock_detail sd where s.stock_id = sd.stock_id;
select * from stock s inner join stock_detail sd on s.stock_id = sd.stock_id;
this will pull all matching records
left join:
select * from stock s, stock_detail sd where s.stock_id = sd.stock_id(+);
select * from stock s left join stock_detail sd on s.stock_id = sd.stock_id;
this will pull all records from stock table and only matching records from stock_detail (101,102,103,104,105)

right join:
select * from stock s, stock_detail sd where s.stock_id(+) = sd.stock_id;
select * from stock s right outer join stock_detail sd on s.stock_id = sd.stock_id;
this will pull only matching records 101 and 102 if there is foreign key defined between these tables, if ther is no define foreign key then
all records from stock_detail and only matching records from stock table will be returned.

11) explain indexing in DB.
Ans:
Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book.

Single-Column Indexes:

A single-column index is one that is created based on only one table column. The basic syntax is as follows:
CREATE INDEX index_name
ON table_name (column_name);

Unique Indexes:

Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows:
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Unique index does not allow duplicate entries.

Composite Indexes:

A composite index is an index on two or more columns of a table. The basic syntax is as follows:
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice.

Implicit Indexes:

Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.

When should indexes be avoided?

Although indexes are intended to enhance a database's performance, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered:
·        Indexes should not be used on small tables.
·        Tables that have frequent, large batch update or insert operations.
·        Indexes should not be used on columns that contain a high number of NULL values.
·        Columns that are frequently manipulated should not be indexed.

14) Explain overall spring MVC flow.
Ans:
http://www.java4s.com/wp-content/uploads/2013/07/Spring-MVC-execution-flow.png
15) is there any other method of threading. except 2.
Ans: third way is using executor framework (java.util.concurrent package):
Example:
Task.java:
package executors;

import java.util.concurrent.TimeUnit;

public class Task implements Runnable
{
       private String name;
        
    public Task(String name)
    {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
   
       @Override
       public void run() {
              // TODO Auto-generated method stub
              Long duration = (long) (Math.random() * 10);
        System.out.println("Doing a task during : " + name);
        try {
                     TimeUnit.SECONDS.sleep(duration);
              } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }

}
BasicThreadPoolExecutorExample.java:
package executors;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class BasicThreadPoolExecutorExample {

       public static void main(String[] args)
    {
              ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
              for (int i = 0; i <= 5; i++)
        {
            Task task = new Task("Task " + i);
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        executor.shutdown();
    }
}
Output:
A new task has been added : Task 0
A new task has been added : Task 1
A new task has been added : Task 2
A new task has been added : Task 3
A new task has been added : Task 4
A new task has been added : Task 5
Doing a task during : Task 0
Doing a task during : Task 5
Doing a task during : Task 4
Doing a task during : Task 3
Doing a task during : Task 2
Doing a task during : Task 1
If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
If object1 and object2 have the same hash code, they do NOT have to be equal too.
In shorter words:

If equal, then same hash codes too.
Same hash codes no guarantee of being equal.














12) how Set is stored internally and how it ensures uniqueness.
13) how can you create annotation.
16) How JSon is converted internally.
17) how you ensure session timeout after few seconds?
5) How can you implement security In rest webservice.
18) what spring @Component annotation do?
8) how HashMap works internally (hashing algorithm)
19) explain database views with type. (refer http://www.tutorialspoint.com/sql/sql-indexes.htm)

18) explain Maven:

What is Maven?

Maven is a project management and comprehension tool. Maven provides developers a complete build lifecycle framework. Development team can automate the project's build infrastructure in almost no time as Maven uses a standard directory layout and a default build lifecycle.