1. explain about ur project
2. what
are the collection u have used in ur project (list, set, or map)
Ans: List, maps
3. write a program to
create user de3fined exceptions
class NoBalanceException extends
Exception
{
public NoBalanceException(String problem)
{
super(problem);
}
}
public class YesBank
{
public static void main( String args[ ] ) throws NoBalanceException
{
int balance = 100, withdraw = 1000;
if (balance < withdraw)
{
NoBalanceException e = new
NoBalanceException("No balance please");
throw e;
}
else
{
System.out.println("Draw
& enjoy, Best wishes of the day");
}
}
}
4. explain the oops concepts of java
5. difference between
string and string buffer and also write a program
import java.io.*;
public class stringBuffer{
public static void main(String[] args) throws Exception{
BufferedReader in =
new BufferedReader(new
InputStreamReader(System.in));
String str;
try{
System.out.print("Enter your name: ");
str = in.readLine();
str += ",
This is the example of SringBuffer
class and it's functions.";
//Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0,str.length());
//append()
strbuf.append("Hello");
strbuf.append("World");
//print HelloWorld
System.out.println(strbuf);
//insert()
strbuf.insert(5,"_Java ");
//print Hello_Java World
System.out.println(strbuf);
//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
//print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf);
//print Hello_Java World
//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf);
//prit Hello Java World
//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
//print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7));
//print lo J
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
//print Helo java World
//capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity());
//print 21
//delete() and length()
strbuf.delete(6,strbuf.length());
System.out.println(strbuf);
//no anything
}
catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
}
}
6. wap to retrieve
the elements from the list, set and map
/*Lists;*/
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// List Example implement with ArrayList
List<String> ls=new ArrayList<String>();
ls.add("one");
ls.add("Three");
ls.add("two");
ls.add("four");
Iterator it=ls.iterator();
while(it.hasNext())
{
String value=(String)it.next();
System.out.println("Value
:"+value);
}
}
}
/*
List Value One
List Value :Three
List Value :two
List Value :four
*/
set
Set interface is part of java.util
package. Set interface can add value elements by add(value) method.
Set can implement TreeSet class.
Set value can get by Iterator
interface.
import
java.util.Iterator;
import java.util.Set;
import
java.util.TreeSet;
public class
SetExample {
public static void main(String[] args) {
// Set example with implement TreeSet
Set<String> s=new
TreeSet<String>();
s.add("b");
s.add("a");
s.add("d");
s.add("c");
Iterator it=s.iterator();
while(it.hasNext())
{
String value=(String)it.next();
System.out.println("Value
:"+value);
}
}
}
/*
Set Value :a
Set Value :b
Set Value :c
Set Value :d
*/
/* map:
Map interface is part of
java.util package. Map interface can add key and value put(key, value) pair
elements. This Map permits null value. Map is interface. Key and value of Map
can get by Set Interface and Map interface through Iterator interface.
Map example give a method, how to use
Map in java.
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapExample {
public static void main(String[] args) {
Map<Object,String> mp=new HashMap<Object, String>();
// adding or set elements in Map by put method key and value pair
mp.put(new Integer(2), "Two");
mp.put(new Integer(1), "One");
mp.put(new Integer(3), "Three");
mp.put(new Integer(4), "Four");
//Get Map in Set interface to get key and value
Set s=mp.entrySet();
//Move next key and value of Map by iterator
Iterator it=s.iterator();
while(it.hasNext())
{
// key=value separator
this by Map.Entry to get key and value
Map.Entry m =(Map.Entry)it.next();
// getKey is used to get key of Map
int key=(Integer)m.getKey();
// getValue is used to get value of
key in Map
String value=(String)m.getValue();
System.out.println("Key
:"+key+" Value :"+value);
}
}
}
Output
Key :1 Value :One
Key :2 Value :Two
Key :3 Value :Three
Key :4 Value :Four
7. explain how did u manage exceptions
in ur project and name some of the exceptions u have faced in the project
8. draw the architecture of the
project
9. explain the
difference between the comparator and comparable interfaces witha program
Java.lang.Comparable
To
implements comparable interface, class must implement a single method
compareTo()
int
a.compareTo(b)
A
comparable object is comparing itself with another object.
You
must modify the class whose instance you want to sort.
So
that only one sort sequence can be created per class.
Java.lang.Comparator
To
implements comparator interface, class must implement a single method compare()
int
compare (a,b)
A
comparator object is comparing two different objects.You build a class separate
from
class whose instance you want to sort. So that multiple sort sequence can be
created
per class.
A comparator object is capable of
comparing two different objects. Comparators can be passed to a sort method
(such as Collections.sort) to allow precise control over the sort order.
Comparators can also be used to control the order of certain data structures
(such as TreeSet or TreeMap).
public interface Comparator {
int compare(T o1, T o2);
}
Refer below code to demonstrate the
collection custom object sorting example using Comparator interface.
package com.net.technicalkeeda;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class EmployeeSort {
/**
* @param args
*/
public
static void main(String[] args) {
List
employees = new ArrayList();
employees.add(new
Employee(10, "Dinesh", 18000));
employees.add(new
Employee(16, "Pankaj", 19000));
employees.add(new
Employee(13, "Mayur", 14000));
employees.add(new
Employee(9, "Pravin", 22000));
System.out.println("----Sort
By Employee Id----");
Collections.sort(employees,
new EmployeeSortById());
printEmployees(employees);
System.out.println("----Sort
By Employee Name----");
Collections.sort(employees,
new EmployeeSortByName());
printEmployees(employees);
}
//
print employee
public
static void printEmployees(List employees) {
for
(Employee e : employees) {
System.out.println("Id->"
+ e.emplId + " Name-> " + e.empName
+
" Salary-> " + e.empSalary);
}
}
}
// Employee Object
class Employee {
public
int emplId;
public
String empName;
public
double empSalary;
public
Employee(int emplId, String empName, double empSalary) {
this.emplId
= emplId;
this.empName
= empName;
this.empSalary
= empSalary;
}
}
// sort by employee id
class EmployeeSortById implements
Comparator {
public
int compare(Employee emp1, Employee emp2) {
int
value = 0;
if
(emp1.emplId > emp2.emplId)
value
= 1;
else
if (emp1.emplId < emp2.emplId)
value
= -1;
else
if (emp1.emplId == emp2.emplId)
value
= 0;
return
value;
}
}
// sort by name
class EmployeeSortByName implements
Comparator {
public
int compare(Employee emp1, Employee emp2) {
return
emp1.empName.compareTo(emp2.empName);
}
}
Output of EmployeeSort.java
----Sort By Employee Id----
Id->9 Name-> Pravin Salary->
22000.0
Id->10 Name-> Dinesh Salary->
18000.0
Id->13 Name-> Mayur Salary->
14000.0
Id->16 Name-> Pankaj Salary->
19000.0
----Sort By Employee Name----
Id->10 Name-> Dinesh Salary->
18000.0
Id->13 Name-> Mayur Salary->
14000.0
Id->16 Name-> Pankaj Salary->
19000.0
Id->9 Name-> Pravin Salary->
22000.0
Java Comparable Example
package com.net.technicalkeeda;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class EmployeeComparableSort {
/**
* @param args
*/
public
static void main(String[] args) {
List
employees = new ArrayList();
employees.add(new
Employee(10, "Dinesh", 18000));
employees.add(new
Employee(16, "Pankaj", 19000));
employees.add(new
Employee(13, "Mayur", 14000));
employees.add(new
Employee(9, "Pravin", 22000));
System.out.println("----Sort
By Employee Id----");
Collections.sort(employees);
printEmployees(employees);
}
//
print employee
public
static void printEmployees(List employees) {
for
(Employee e : employees) {
System.out.println("Id->"
+ e.emplId + " Name-> " + e.empName
+
" Salary-> " + e.empSalary);
}
}
}
// Employee Object
class Employee implements Comparable {
public
int emplId;
public
String empName;
public
double empSalary;
public
Employee(int emplId, String empName, double empSalary) {
this.emplId
= emplId;
this.empName
= empName;
this.empSalary
= empSalary;
}
public
int compareTo(Employee otherEmployee) {
int
id = ((Employee) otherEmployee).emplId; // same type object
if
(this.emplId > id)
return
1;
else
if (this.emplId < id)
return
-1;
else
return
0;
}
}
Output of EmployeeComparableSort.java
----Sort By Employee Id----
Id->9 Name-> Pravin Salary->
22000.0
Id->10 Name-> Dinesh Salary->
18000.0
Id->13 Name-> Mayur Salary->
14000.0
Id->16 Name-> Pankaj Salary->
19000.0
10.
explain the life cycle of struts
Steps for request lifecycle in strut
two applications:-
1)
In first step user sends a request to the server for some resource.
2)
The filterDispatcher accept the request and then it determines the
appropriate action.
3)
The interceptors configured for applying the common functionalities like
workflow, validation, and file upload etc and these functionalities are
automatically to the request. The Interceptors are helps to specify the
“request-processing lifecycle” for an action. Interceptors are configured to
apply the common functionalities like workflow, validation etc to the request.
4)
The action method executed to perform the database related operations
such as storing and retrieving data from the database.
5)
The result rendered the output.
6)
The request returns through the interceptors in the reverse order. The retuning request permits us to perform
the clean up or additional processing.
7)
The final step is returned to the servlet container which sends the
output to the user browser.
The flow of strut application is given
below.
The ActionServlet stands as a back
bone of the struts applications. First the request is handled by the either
doGet() or doPost() method of the Action Servlet. After that the Action Servlet calls the process() method of
its own. This method gets the Current Request Processor associated with the
request. Then this request processor calls its process() method. The Request
Processor also a type of Servlet. This is the actual place where the request is
handled. This method reads the struts-config.xml file and find outs the Action
class by seeing the request URL path.
Eg: -
?
1
2
3
4
5
6
Incoming request URL path is:/login
struts-config.xml:
<action path=“/login”
type=“Test.LoginClass”>
<forward name=“Succes”
path=“/Welcome.jsp”/>
<forward name=“failure”
path=“/Login.jsp”/>
</action>
After identifying the Action class it
checks the whether the request is associated with any form bean. This can be
checked by using the name attribute of the action element from the
struts-config.xml.
Eg: -
?
1
2
3
<form-beans>
<form name=“loginForm”
type=“Test.LoginForm”/>
</form-beans>
?
1
2
3
4
5
<action-mappings>
<action
path=“/login”type=“Test.LoginClass”
name=“loginForm”>
…..
</action-mappings>
Then it made the instance of
ActionForm and calls the corresponding getter and setter methods for the
incoming request parameters. We can validate the request parameter by calling
the validate() method in ActionForm. For this we need to specify
validate=“true” and input=“/Login.jsp” in struts-config.xml file. Now the
actual request is handled by the Action class by calling the execute() method.
Output of this method is the response of the request and the return type of
this request is ActionMappings.
The browser creates a request to the
struts application, the request is processed through ActionServlet. Here the
ActionServlet indicates the controller of the strut application. The controller
fill the ActionForm or view the object with the HTML form data and invokes it’s
validate() method. The controller executes the action object. The action object is also a controller. The
action controller interfaces with model components and make data for view. The
action controller forwards control to the JSP or view page. The JSP or view
uses model data to generate a response to the browser.
For the compilation of the entire
development cycle we uses strut 2 frameworks. This framework includes building,
developing and maintaining whole application. The features of strut 2 framework
are,
1)
Struts Architecture : – In the architecture of the strut first the web
browser requests a resource for which the Filter Dispatcher decides the
suitable action. After one request is made the interceptors use the available
functions and after that the Action method executes all the functions such as
storing and retrieving data from a database. Then the result can be seen on the
output of the browser in HTML, PDF, images or any other.
2)
Struts Tags : – Tags in Strut 2 permits to developing dynamic web
applications with less number of coding. These tags include the output data but
also provide style sheet driven markup that in turn helps in creating pages
with less code. Here the tags also helps for validation and localization of
coding that in turn offer more utilization. The less number of codes also makes
it easy to read and maintain.
3)
Struts MVC: – The Model View Controller in Strut 2 framework acts as a
coordinator between application(s) model and web view. Its Controller and View
components can come together with other technology to develop the model. The
framework has its library and markup tags to present the data dynamically.
4)
Struts Configuration: – The configuration provides a deployment
descriptor to initialize resources in XML format. The initialization takes
place simply by scanning all the classes using Java packages or you can use an
application configuration file to control the entire configuration. Its
general-purpose defaults permit to using struts directly Out of the box. The
configuration files are reloaded that permits to changes without restarting the
web container.
5)
Other Struts features
All framework classes are based on
interfaces and core interfaces are independent from HTTP.
Check boxes do not require any kind of
special application for false values.
Any class can be used as an action
class and one can input properties by using any JavaBean directly to the action
class.
Strut 2 actions are Spring friendly
and so easy to Spring integration.
AJAX theme enables to make the
application more dynamic.
Portal and servlet deployment are easy
due to automatic portlet support without altering code.
The request handling in every action
makes it easy to customize, when required.
11.
difference between dispatch and lookup dispatch action and wap for bothe of
them
LookupDispatchAction is subclass of
DispatchAction.
In case of DispatchAction, you have to
declare the method name in the JSP page.
For Example :
http://localhost:8080/emp/empaction.do?step=add
// IN CASE OF DispatchAction
here step=add , we are delaring method
name in JSP.
or
<html:submit
property="step">Add</html:submit> //IN CASE OF
DispatchAction
so we can't use localization for
button.
To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.
In the LookupDispatchAction :
For example :
If there are three operation like add,
delete, update employee.
You can create three different Actions
?
AddEmpAction, DeleteEmpAction and
UpdateEmpAction.
This is a valid approach, although not
elegant since there might be duplication of code across
the Actions since they are related.
LookupDispatchAction is the answer to this
problem. With LookupDispatchAction,
you can combine all three Actions into one.
Example :
Step 1.
three buttons might be
<html:submit
property="step">
<bean:message
key="button.add"/>
</html:submit>
<html:submit
property="step">
<bean:message
key="button.delete"/>
</html:submit>
<html:submit
property="step">
<bean:message key="button.update"/>
</html:submit>
//No need method name declaration in
JSP . Button name from resource bundle.
Step 2.
In the the Resource Bundle. //Here you
can add localization.
button.add=Add
button.delete=Delete
button.update=Update
Step 3.
Implement a method named
getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method
returns a java.util.Map. The
keys used in the Map should be also
used as keys in Message Resource
Bundle.
public class EmpAction extends
LookupDispatchAction {
public Map getKeyMethodMap()
{
Map map = new HashMap();
map.put("button.add",
"add");
map.put("button.delete",
"delete");
map.put("button.update",
"update");
}
public ActionForward add(ActionMapping
mapping,
ActionForm form, HttpServletRequest
request,
HttpServletResponse response) throws
Exception
{
//your logic
mapping.findForward("add-success");
}
public ActionForward
delete(ActionMapping mapping,
ActionForm form, HttpServletRequest
request,
HttpServletResponse response) throws
Exception
{
//your logic
mapping.findForward("delete-success");
}
public ActionForward
update(ActionMapping mapping,
ActionForm form, HttpServletRequest
request,
HttpServletResponse response) throws
Exception
{
//your logic
mapping.findForward("update-success");
}
}
in struts-config.xml
<action path="/empaction"
input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
<forward
name="add-success"
path="addEmpSuccess.jsp"
redirect="true"/>
<forward
name="delete-success"
path="deleteEmpSuccess.jsp"
redirect="true"/>
<forward
name="update-success"
path="updateEmpSuccess.jsp"
redirect="true"/>
</action>
for every form submission,
LookupDispatchAction does the
reverse lookup on the resource bundle
to get the key and then gets the method
whose name is associated with the key
from
getKeyMethodmap().
Flow of LookupDispatchAction:
a) Form the button name
"Add" get the key "button.add" fro resource bundle.
b) then in the Map getKeyMethodMap()
find the value associated with the key "button.add".
c) value from the Map is
"add" . then call add() method of the same action class.
12.
what design patterns u have implemented in u r project(n singleton and factory,
mvc)
Ans: Mvc architecture
13. wap
to demonstrate table per class or table per concrete class or table per
subclass in hibernate
One Table Per Class Hierarchy example
Suppose we have a class Person with
subclass Employee. The properties of each class are:
* class Person
-
firstname
-
lastname
* class Employee
-
joining_date
-
department_name
In One Table per Class Hierarchy
scheme, we store all the class hierarchy in a single SQL table. A discriminator
is a key to uniquely identify the base type of the class hierarchy.
Following are the advantages and
disadvantages of One Table per Class Hierarchy scheme.
Advantage
This hierarchy offers the best
performance even for in the deep hierarchy since single select may suffice.
Disadvantage
Changes to members of the hierarchy
require column to be altered, added or removed from the table.
Create Database Table to persist Class
Hierarchy
CREATE TABLE `person` (
`person_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`joining_date` DATE NULL DEFAULT NULL,
`department_name` VARCHAR(50) NULL DEFAULT NULL,
`discriminator` VARCHAR(20) NOT NULL,
PRIMARY KEY (`person_id`)
)
The PERSON table will store both
Employee and Person objects.
Hibernate Inheritance: XML Mapping
Following is the example where we map
Employee and Person entity classes using XML mapping.
File: Person.java
package net.viralpatel.hibernate;
public class Person {
private Long personId;
private String firstname;
private String lastname;
// Constructors and Getter/Setter methods,
}
File: Employee.java
package net.viralpatel.hibernate;
import java.util.Date;
public class Employee extends Person {
private Date joiningDate;
private String departmentName;
// Constructors and Getter/Setter methods,
}
File: Person.hbm.xml
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="net.viralpatel.hibernate">
<class name="Person" table="PERSON"
discriminator-value="P">
<id name="personId" column="PERSON_ID">
<generator
class="native" />
</id>
<discriminator column="DISCRIMINATOR"
type="string" />
<property name="firstname" />
<property name="lastname" column="lastname" />
<subclass name="Employee" extends="Person"
discriminator-value="E">
<property
name="departmentName" column="department_name" />
<property
name="joiningDate" type="date"
column="joining_date" />
</subclass>
</class>
</hibernate-mapping>
Note that we have defined only one
hibernate mapping (hbm) file Person.hbm.xml. Both Person and Employee model
class are defined within one hbm file.
<discriminator> tag is used to
define the discriminator column.
<subclass> tag is used to map
the subclass Employee. Note that we have not used the usual <class> tag
to map Employee as it falls below in the hierarchy tree.
The discriminator-value for Person is
defined as “P” and that for Employee is defined “E”, Thus, when Hibernate will
persist the data for person or employee it will accordingly populate this
value.
14.
difference between load and get in hibernate
Ans:
Actually, both functions are use to
retrieve an object with different mechanism, of course.
1. session.load()
It will always return a “proxy”
(Hibernate term) without hitting the database. In Hibernate, proxy is an object
with the given identifier value, its properties are not initialized yet, it
just look like a temporary fake object.
If no row found , it will throws an
ObjectNotFoundException.
2. session.get()
It always hit the database and return
the real object, an object that represent the database row, not proxy.
If no row found , it return null.
It’s about performance
Hibernate create anything for some
reasons, when you do the association, it’s normal to obtain retrieve an object
(persistent instance) from database and assign it as a reference to another
object, just to maintain the relationship. Let’s go through some examples to
understand in what situation you should use session.load().
1. session.get()
For example, in a Stock application ,
Stock and StockTransactions should have a “one-to-many” relationship, when you
want to save a stock transaction, it’s common to declared something like below
Stock stock =
(Stock)session.get(Stock.class, new Integer(2));
StockTransaction stockTransactions =
new StockTransaction();
//set stockTransactions detail
stockTransactions.setStock(stock);
session.save(stockTransactions);
Output
Hibernate:
select ... from mkyong.stock stock0_
where stock0_.STOCK_ID=?
Hibernate:
insert into mkyong.stock_transaction (...)
values (?, ?, ?, ?, ?, ?)
In session.get(), Hibernate will hit
the database to retrieve the Stock object and put it as a reference to
StockTransaction. However, this save process is extremely high demand, there
may be thousand or million transactions per hour, do you think is this
necessary to hit the database to retrieve the Stock object everything save a
stock transaction record? After all you just need the Stock’s Id as a reference
to StockTransaction.
2. session.load()
In above scenario, session.load() will
be your good solution, let’s see the example,
Stock stock =
(Stock)session.load(Stock.class, new Integer(2));
StockTransaction stockTransactions =
new StockTransaction();
//set stockTransactions detail
stockTransactions.setStock(stock);
session.save(stockTransactions);
Output
Hibernate:
insert into mkyong.stock_transaction (...)
values (?, ?, ?, ?, ?, ?)
In session.load(), Hibernate will not
hit the database (no select statement in output) to retrieve the Stock object,
it will return a Stock proxy object – a fake object with given identify value.
In this scenario, a proxy object is enough for to save a stock transaction
record.
Exception
In exception case, see the examples
session.load()
Stock stock =
(Stock)session.load(Stock.class, new Integer(100)); //proxy
//initialize proxy, no row for id 100, throw
ObjectNotFoundException
System.out.println(stock.getStockCode());
It will always return a proxy object
with the given identity value, even the identity value is not exists in
database. However, when you try to initialize a proxy by retrieve it’s
properties from database, it will hit the database with select statement. If no
row is found, a ObjectNotFoundException will throw.
org.hibernate.ObjectNotFoundException:
No row with the given identifier exists:
[com.mkyong.common.Stock#100]
session.get()
//return null if not found
Stock stock =
(Stock)session.get(Stock.class, new Integer(100));
System.out.println(stock.getStockCode());
//java.lang.NullPointerException
It will always return null , if the
identity value is not found in database.
Conclusion
There are no always correct solution,
you have to understand the differential in between, and decide which method is
best fix in your application.
15.
write a join operation in HQL
Ans:
16 write a criteria query to retrieve
the elements from the pojo classes
17 explain and write a rpogram to
demonstrate the constructor, setter and method injection in spring.
18 what is auto wiring in spring
19 write a program to demonstrate bean
inheritance and bean factory inheritance
20 what are the various scopes of
spring bean
21 explain the integration of spring
and hibernate with a program
22 explain spring mvc architecture
well
23 explain about abstract constroller
and simple form controller in spring with a program
2