Search This Blog

Monday 30 January 2017

Java Quiz 01


Take the Java Quiz


    1.     Which of the following is true Statement?
A.    A class that is abstract cannot not be instantiated
B.    final variable are constant variable
C.    A static variable indicates there is only one copy of that variable
D.    A method defined as private indicates that it is accessible to all other classes in the same package


    2.     Which is a valid keyword in java?
A.    int
B.    Boolean
C.    Integer
D.    Instanceof


    3.     Given :
public class A{
 class B{
  }
}
On compiling the code using
javac A.java
What all .class files will be created?"
A.      A.class
B.      B.class
C.      A.class AND B.class
D.      A.class AND A$B.class

     4.     Given:
public class TestString1 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}
What is the output?
A.    42
B.    420
C.    462
D.    42042

    5.     Identify the correct syntax to create a user defined exception which handles exception at compile time
A.    class MyException extends Exception {}
B.    class MyException extends RuntimeException {}
C.    class MyException extends Error {}
D.    None from the option

    6.     Which of the following command will create a non-executable jar file
A.    java -cf jarname.jar classfiles
B.    java  jarname.jar classfiles
C.    java -cf classfiles jarname.jar
D.    None from the option


    7.     Exception given by  compiler  at compile time  are known as
A.    checked exception
B.    unchecked exception
C.    public exception
D.    None from the option

    8.     Which of the following is correct Statement for annotation?
A.    annotation is information for compiler
B.    none of the options
C.    annotation is use for compilation
D.    annotation is use to handle exception

    9.     Which class in java which can parse primitive types and strings using regular expressions
A.    Scanner
B.    Reader
C.    InputStream
D.    BufferedReader


   10.  Which of the following is part of Character stream?
A.    FileInputStream
B.    BufferedInputStream
C.    FileReader
D.    ObjectInputStream

   11.  Given:
import java.util.*;
public class Example {
public static void main(String[] args) {
// insert code here
set.add(new Integer(2));
set.add(new Integer(1));
System.out.println(set);
}
}
Which code, inserted at line // insert code here, guarantees that this program will
output [1, 2]?
A.    Set set = new TreeSet();
B.    Set set = new HashSet();
C.    Set set = new LinkedHashSet();
D.    None from the option

    12.  Given a class whose instances, when found in a collection of objects, are sorted by using the compare() method, which  statements are true?
A.    The class implements java.lang.Comparable.
B.    The class implements java.lang.Comparator
C.    The interface used to implement sorting allows this class to define only one sort
sequence
D.    The interface used to implement sorting allows this class to define many different sort
sequences.




    13.  Which interface provides the capability to store objects using a key-value pair?
A.    Java.util.Map
B.    Java.util.List
C.    Java.util.Set
D.    Java.util.Collection

    14.  Which type of driver converts JDBC calls into the network protocol used by the database management system directly?
A.    Type 1 driver
B.    Type 2 driver
C.    Type 3 driver
D.    Type 4 driver

    15.  Which of the following methods are needed for loading a database driver in JDBC?
A.    registerDriver() method
B.    Class.forName()
C.    getDriver()
D.    getConnection()

    16.  All the method should be preceded with the keyword _____________ , If the methods of an object should only be executed by one thread at a time
A.    Asynchronized
B.    Serialized
C.    Synchronized
D.    None from the option

    17.  Which of the following synchronized method or block will compile and run without exception?
A.    private synchronized Object o;
B.    public synchronized void go() { /* code here */ }
C.    private synchronized(this) void go() { /* code here */ }
D.    void go() {
synchronized(Object.class) { /* code here */ }

    18.  An object that can be used to get information about the types and properties of the columns in a ResultSet object is _____________________
A.    ResultSetMetaData
B.    DatabaseMetaData
C.    ColumnMetaDeta
D.    None from the option
   19.  Given:
public class MyThread implements Runnable{
//your code here
}

Which method definition in // your code here completes the class?
A.    void run()
B.    void start()
C.    void execute()
D.    void runThread()

   20.  A call to this methods invoked on a thread will wait and not return until either the thread has completed or it is timed out after the specified time.
A.    sleep()
B.    yeild()
C.    join()
D.    run()

Wednesday 25 January 2017

Factory Design Pattern in Java

Factory Design Pattern in Java
Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Motivation
Factory Design pattern is also known as Virtual Constructor, the Factory Method is related to the idea on which libraries work: a library uses abstract classes for defining and maintaining relations between objects. One type of responsibility is creating such objects.
The library knows when an object needs to be created, but not what kind of object it should create, this being specific to the application using the library.

The Factory method works just the same way: it defines an interface for creating an object, but leaves the choice of its type to the subclasses, creation being deferred at run-time.

 A simple real life example of the Factory Method is the Bank Account.
A user wants to open an Account in a bank.  A user can open either a Saving Account, Current Account, Salary Account,  Demat Account based on their requirement.
Depending on the requirement the subclass object for any of the account type can be created can be created.

Applicability
Use the Factory Method pattern when
  •          A class can't anticipate the class of objects it must create.
  •          A class wants its subclasses to specify the objects it creates.
  •          Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Consequences
  •          Factory methods eliminate the need to bind application-specific classes into your code.
  •           Provides hooks for subclasses. Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object.
  •          Connects parallel class hierarchies. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class.

 Implementation
We're going to create an Account interface and concrete classes implementing the Account interface.
A factory class AccountFactory would be responsible for returning object.
FactoryPatternDemo  class will use AccountFactory to get an Account object.
It will pass information (Saving / Current / Salary / Demat) to AccountFactory to get the type of object it needs.
Create an Interface Account
public interface Account {
      public void openAccount();
}

Create Classes SavingAccount, SalaryAccount, CurrentAccount, DematAccount which implements the Account interface.
public class SavingAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Savings Account");
      }
}

public class CurrentAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Current Account"); 
      }
}

public class SalaryAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Salary Account");
      }
}

public class DematAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Demat Account");   
      }
}

Create the AccountFactory Class which returns Objects of the Subclasses.
public class AccountFactory {
public Account getAccountType(String accountType){
      if(accountType==null){
            return null;
      }
            if(accountType.equalsIgnoreCase("saving")){
                  return new SavingAccount();
            }
            else if(accountType.equalsIgnoreCase("current")){
                  return new CurrentAccount();
            }
            else if(accountType.equalsIgnoreCase("salary")){
                  return new SalaryAccount();
            }
            else if(accountType.equalsIgnoreCase("demat")){
                  return new DematAccount();
            }
      return null;     
}
}

Create the FactoryPatternDemo with the main method
public class FactoryPatternDemo {
public static void main(String[] args) {
      AccountFactory accountFactory=new AccountFactory();
     
      Account saving=accountFactory.getAccountType("saving");
      saving.openAccount();
     
      Account current=accountFactory.getAccountType("current");
      current.openAccount();
     
      Account salary=accountFactory.getAccountType("salary");
      salary.openAccount();
     
      Account demat=accountFactory.getAccountType("demat");
      demat.openAccount();
}
}

Execute the above class , we get the following output.


Factory Design Pattern in Java
Factory Design Pattern in Java













Monday 23 January 2017

Difference Between Servlet and JSP

This post highlights the difference between JSP and Servlet technologies.

Java Servlet technology and JavaServer Pages (JSP pages) are server-side technologies that become the standard way to develop web applications.

Most importantly, if used effectively by following best practices, servlets and JSP pages help separate presentation from content.

Servlets support a request and response programming model. When a client sends a request to the server, the server sends the request to the servlet. The servlet then constructs a response that the server sends back to the client. When a client request is made, the service method is called and passed a request and response object. The servlet first determines whether the request is a GET or POST operation. It then calls one of the following methods: doGet or doPost. The doGet method is called if the request is GET, and doPost is called if the request is POST.

Adding more, Servlets are Java classes that can generate dynamic HTML content using print statements.
out.println("<html><head><title>"+thisIsMyMessage+"</title></head>");
So, you can embed HTML code into Java code.

A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is .jsp rather than .html or .htm, which tells the server that this page requires special handling that will be accomplished by a server extension. When a JSP page is called, it will be compiled (by the JSP engine) into a Java servlet.

Importantly, we can add dynamic content or Java Code inside an HTML Tag using JSP’s Scriplets.
And scriptlets, this is code fragments like:
<% String message = "Hello !"%>
<H2> Welcome and  <%=message%>! </H2>
So, you can embed Java code into HTML code.





SERVLET
JSP
A servlet is a server-side program and written purely on Java.
JSPs are HTML pages with .jsp extension. JSP’s are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming.
Executes inside a Web server, such as Tomcat
A JSP program is compiled into a Java servlet before execution. Once compiled into a servlet, it's life cycle will be same as of servlet. But, JSP has it's own API for the lifecycle.
Servlets run faster than JSP
JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file.
Servlet has the life cycle methods init(), service() and destroy()
JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy()
Difficult to write as one has to write HTML tags within quotes(“<HTML>”) in Java. Mixing HTML content inside Java is tedious.
Easier to write than servlets as it is similar to HTML
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques.
One of the key advantage is we can build custom tags using JSP API ,  which can be available as the re-usable components with lot of flexibility
In MVC architecture Servlet acts as controller.
In MVC architecture JSP acts as view.
Servlet advantages include:
·  Performance: get loaded upon first request and remains in memory indefinitely.
·  Simplicity: Run inside controlled server environment.
·  Session Management : overcomes HTTP's stateless nature
·  Java Technology : network access, Database connectivity, j2ee integration
JSP Provides an extensive infrastructure for:
·         Tracking sessions.
·         Managing cookies.
·         JSP is Extensible: Can create custom tags to extend the JSP functionality.
·         Separation of roles: Clearly identifies separation of roles for Developers, Content Authors/ Graphic Designers/ Web Masters.