Tuesday, December 29, 2009

Enterprise application with MyEclipse 6 and MySQL 5

Task #1
Copy the mysql-ds.xml from directory - jboss-4.2.2.GA\docs\examples\jca\
Edit it (jndi-name is used later)
Paste it into directory - jboss-4.2.2.GA\server\all\deploy\

Task #2
Paste all JARs related to database driver into directory - jboss-4.2.2.GA\server\all\lib\

Task #3
Select Application Server -> Jboss -> Jboss 4.x
Choose “Enable”
Click on “Browse” for Jboss home directory eg. C:\ jboss-4.2.2.GA
Enter “Server name” as all
Click “OK”


Task #4
Step 1: File -> New -> Enterprise Application project
Step 2: Enter “Project Name”
Check “Use Default Loaction”
Choose “Java EE 5.0”
Check “New web module project” and “New EJB module project”
Step 3: Press “Next” button (it will show web project module detail)
Step 4: Press “Next” button (it will show EJB project module detail)
Check “ Add support for entity beans (add JPA capabilities)”
Press “Next” button
Step 5: Click on “Create new Driver”
Select “Driver template” eg. MySQL Connector/J
Click on “Add JARs” and browse for JARs
Select “Driver classname” eg. com.mysql.jdbc.Driver
Enter “Driver name” eg. com.mysql.jdbc.Driver
Edit “Connection URL” eg. jdbc:mysql://localhost:3306/test
Enter “User name”
Enter “Password”
Check “Save password”
Step 6: Choose “Display the selected schemas”
Press “Add” button then click “OK”
Select schema to be displayed {test} then click “OK” then click “Finish”
Step 7: click “Update List” and select “Catalog/Schema”
Enter “JNDI Data Source” eg. java:{jndi-name in mysql-ds.xml file}

Task #5
Step 1: Right Click on EJB-Module -> MyEclipse ->Generate Entities..
Step 2: Select form “Available tables” and then “Add”
Click on “Next”
Step 3: Browse for Destination “Java Package”
Check “Entity Bean Generation”
Check “Entity facade”, “findby methods” and “Generate remote interface”
Click on “Next”
Step 4: click on “Next”
Step 5: all checkbox unchecked
Click on “Finish”
Click on “OK”

Monday, December 21, 2009

Hibernate Interview Questions

Struts Interview Questions

Q. What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

Q. What are the components of Struts?
Struts components can be categorize into Model, View and Controller:
Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components. Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

Q. What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

Q. Role of ActionServlet?
1)Process user requests
2)Determine what the user is trying to achieve according to the request
3)Pull data from the model (if necessary) to be given to the appropriate view,
4)Select the proper view to respond to the user
5)Validate and populate the form beans
6)Is responsible for initialization and clean-up of resources

Q. What is the ActionForm/ form bean?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

Q. What are difference between form beans and Java bean?
form bean extends ActionForm class and has validate(mapping, request) and reset() methods that are executed by controller.

Q. What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

JSP Interview questions

Servlet Interview Questions

Saturday, December 19, 2009

Core Java Interview Questions

Q1: What will be the output of following code?
class Test {
Test(int x){
System.out.print("Test("+x+")");
}
}

class Q1{
static Test t1 =new Test(1);
Test t2=new Test(2);
static Test t3 = new Test(3);
public static void main(String[] args) {
Q1 q=new Q1();
}
}

now this question for testing the sequence of fields to initialize.
Output - Test(1)Test(3)Test(2)

Q2: What will be the output of following code?
byte b =0;
while(++b>0)
;
System.out.println("Welcome to Java");
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q3: What will be the output of following code?
if(new Boolean("true")==new Boolean("true"))
System.out.println("TRUE");
else
 System.out.println("FALSE");
FALSE (they are two diffrenent objects)

Q4: What will be the output of following code?
class AA{
static void show(){
System.out.println("A");
}
}
class B extends AA{
static void show(){
System.out.println("B");
}
}
class Test {
public static void main(String[] args) {
AA a=new AA();
a.show();
B b=new B();
b.show();
a=b;
a.show();
b=a;
b.show();

}}
Answer: b=(B)a Compilation Error

Q5: What will be the output of following code?
class AA{
static void show(){
System.out.println("A");
}
}
class B extends AA{
void show(){
System.out.println("B");
}}
Answer: Compilation Error (Instance method cannot override the static method from class AA)

Q6: What will be the output of following code?
class AA{
void show(){
System.out.println("A");
}
}
class B extends AA{
static void show(){
System.out.println("B");
}}
Answer: Compilation Error (static method can not hide the instance method from AA)

Q7: What will be the output of following code?
class Test {
public static void main(String[] args) {
B b= new B();
b.show();
B.show();
}
}

class AA{
static void show(){
System.out.println("A");
}
}
class B extends AA{
}

Output: (You can access static method with subclass reference)
A

A


Q8: What will be the output of following code?
class Test {
static int x=11;
public static void main(String[] args) {

int x =2;
System.out.println(x);
}}
Output: 2

Q9: What will be the output of following code?
ArrayList list = new ArrayList();
list.add("B");
list.add("A");
list.add(new Integer(23));
Collections.sort(list);
Answer: Compile but not run. Throw runtime exception – ClassCastException.Collection.sort(List) is used to sort parameterized list. If you comment out list.add(new Integer(23)); then it will run.

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Q2: What will be the output of following code?
code code
Welcome to Java (because in byte, when b=127 and then next iteration it will be -1)

Multithreading

What is multithreading:

Java support multithreading programing. A (multithreaded) program contains two or more parts that can run concurrently. Each part of such program is called a "Thread" and each thread defines seperate path of exectution.

Every thread has own independent “call stack”.
Multitasking – 1) process based multitasking, 2) thread based multitasking.
1) Process is a program in running state. In process based multitasking, which allows processes (i.e. programs) to run concurrently.
2) A thread is a part of program. In thread-based multitasking, multiple threads in a program run concurrently.

Advantages of thread-based multitasking over process-based multitasking are
1) At runtime, Threads in a program shares same memory space.
2) Context switching between thread is less expensive.
3) Cost of communication between threads is relatively low.
4) Multithreading can make your program more responsive, interactive and run faster than non-threaded version.


What is Main Thread:
The main thread is created automatically when your program is started, it can controlled through a Thread object. You can obtain the reference of it by calling the method currentThread() which is a public static member of Thread.

Case #1
package threads;
public class MainThread {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("Main Thread: "+t);
}
}

Case #2
package threads;
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet{
public void paint(Graphics g) {
Thread t = Thread.currentThread();
g.drawString("Main Thread: "+t,0, 100);
}
}


Creating Threads:

The thread is an independent sequential path of execution within a program. At runtime, threads in a program shares common memory space so they share both data and code (i.e. they are lightweight compared to process).
A thread in Java is represented by an object of the java.lang.Thread class. Implementing thread is achieved in two ways-
implementing the java.lang.Runnable interface.
extending the java.lang.Thread class

The Thread class implement the Runnable interface and the Runnable interface has only one method that is public void run().

At minimum you have to know following methods of Thread class:
public void run()
public void start()
public static void sleep()
public static void currentThread()
public static void yield()
public void join()
public boolean isAlive()
public String getName()
public void setPriority()

Constructors of the Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)

Implementing the Runnable interface:
To implement Runnable interface, a class need to implement a single method called run().
public void run(){
// code
}
Steps:
1) A class implement the Runnable interface, providing the run() method that will be executed by the thread.
2) An object of Thread class is created by passing a Runnable object as argument to thread constructor.

3) The start() method is invoked on Thread object created in previous step.


package threads;

public class Test {
public static void main(String[] args) {
ThreadRunnable r = new ThreadRunnable();
Thread t1=new Thread(r);
t1.start();
try {
for(int i=0;i<5;i++){ i="0;i<5;i++){">


Extending the Thread class:
Steps:
1) A class extending the Thread class overrides the run() method from the Thread class.
2) This subclass may call may call a Thread constructor explicitly in its constructor to initialize the thread using super().
3) The start() method inherited form the Thread class is invoked on the object of the class to make the thread eligible for running.

package threads;

public class Test {
public static void main(String[] args) {
Thread1 t1=new Thread1();
t1.start();
try {
for(int i=0;i<5;i++){ i="0;i<5;i++){">

When creating threads, implementing the Runnable interface is good programming practice because you can extend other class as well as implementing the Runnable interface.


Synchronization:
When two or more threads need access to shared resource, they need some way to ensure tha the resource will be used by only one thread a time. The process by which this is achieved is called Synchronization. Each resource in java has its own lock. So threads first obtain the lock then use that resource.
You can synchronize your code in either of two ways -
Synchronized Methods:
To enter the object’s lock, you, just call a method that has been modified with synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on same object have to wait. A thread relinquishes the lock simply by returning from synchronized method, allowing the next thread waiting for this lock to proceed.

Synchronized blocks:
Imagine that you want to synchronize access to objects of the class that was not designed for multithreaded access. That is this class does not use synchronized methods. This class was not created by you but by the third party and you have not right to change the code of that class.
Solution of this problem is very simple: You simply put calls to the methods defined by this class inside a synchronized block.
Synchronized(objectRef){
ObjectRef.method1();
// statements
}

Interthread Communication:

In Java, threads communicate using three methods – wait(), notify(), and notifyAll(). These methods are implemented in Object class, so all classes have these methods. All three methods can be called only from within a synchronized context.
wait() tells the calling thread to give up the lock and go to sleep until some other thread enters the same lock and calls notify().
notify() wakes up a thread that is waiting(by called wait) for the same object.
notifyAll() wake up all the threads that called wait() on the same object. One of the threads will be granted the access.
Methods in Object class:
final void wait() throws InterruptedException
final void notify()
final void notifyAll()


package threads;
public class PC {
public static void main(String[] args) {
Q q=new Q();
new Thread(new Consumer(q)).start();
new Thread(new Producer(q)).start();
}
}
class Q{
int n;
boolean valueSet=false;
synchronized int get(){
while(!valueSet)
try{
System.out.println("before wait in GET");
wait();
}catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: "+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n){
while(valueSet)
try{
System.out.println("before wait in PUT");
wait();
}catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n=n;
valueSet=true;
System.out.println("Put: "+n);
notify();
}
}
class Producer implements Runnable{
Q q;
Producer(Q q){
this.q=q;
}
public void run() {
int i=0;
while(i<100){ // condition for stooping the loop after 100;
q.put(i++);
}
}
}
class Consumer implements Runnable{
Q q;
Consumer(Q q){
this.q=q;
}
public void run() {
int k=0;
while(k<100){ //condition is only to stop the loop there no other use of k
q.get();
k++;
}
}
}


What is multithreading:
Java support multithreading programing. A (multithreaded) program contains two or more parts that can run concurrently. Each part of such program is called a "Thread" and each thread defines seperate path of exectution

Monday, December 14, 2009

Difference between Java 1.4 and Java 1.5

These features are in Java 1.5 not in Java 1.4( jdk 1.4)
1) Variable Argument List:
2) Enhanced for loop:
3) Autoboxing and Unboxing:
4) Formatted Output:
int i=0;
System.out.printf("i is %d", i);

5) Enhanced Input:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
int n = Integer.parseInt(str);
System.out.println(n+10);

6) Generics:
7) Static Import:

Saturday, December 12, 2009

DAO, BEAN, DATEFORMATTER, BASECONNECTION

package com.vikas.bean;
import java.util.Date;
import com.mysql.jdbc.Blob;
public class EmployeeBean { private String name; private double salary; private String bday; private Blob image; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; }
public String getBday() { return bday; } public void setBday(String bday) { this.bday = bday; } public Blob getImage() { return image; } public void setImage(Blob image) { this.image = image; } }

package com.vikas.commons;
import java.sql.Connection;import java.sql.DriverManager;
public class BaseConnection { private static Connection conn=null; public static Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","vikas123"); }catch (Exception e) { e.printStackTrace(); } return conn; } public static void main(String[] args) { System.out.println(getConnection().toString()); }
}


package com.vikas.commons;
import java.text.SimpleDateFormat;import java.util.Date;
public class DateFormatter { public static String dateToString(Date date){ try{ SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy"); if(date!=null){ String sdate=sdf.format(date); return sdate; } } catch(Exception e) { e.printStackTrace(); } return null; } public static Date stringToDate(String sDate){ try{ SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy"); if(sDate!=null){ Date date=sdf.parse(sDate); return date; } } catch(Exception e) { e.printStackTrace(); } return null; } public static String stringToSqlDate(String sDate){ try{ SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy"); if(sDate!=null){ Date date=sdf.parse(sDate); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); return sqlDate.toString(); } } catch(Exception e) { e.printStackTrace(); } return null; }
}

package com.vikas.dao;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.Date;
import com.vikas.bean.EmployeeBean;import com.vikas.commons.BaseConnection;import com.vikas.commons.DateFormatter;
public class EmployeeDAO { public void save(EmployeeBean emp){ try{ Connection conn = BaseConnection.getConnection(); /*Statement stmt = conn.createStatement(); String sql = "INSERT INTO employee(name,salary,birthday) VALUES('"+emp.getName()+"',"+emp.getSalary()+",'"+DateFormatter.stringToSqlDate(emp.getBday())+"')"; System.out.println(sql); stmt.executeUpdate(sql);*/ PreparedStatement pst = conn.prepareStatement("INSERT INTO employee(name,salary,birthday) VALUES(?,?,?)"); pst.setString(1, emp.getName()); pst.setDouble(2, 10000); pst.setString(3, DateFormatter.stringToSqlDate(emp.getBday())); //pst.setDate(3, DateFormatter.stringToDate(emp.getBday())); pst.executeUpdate(); System.out.println("Data Saved"); }catch (Exception e) { e.printStackTrace(); } } public void update(EmployeeBean emp){ try{ Connection conn = BaseConnection.getConnection(); PreparedStatement pst = conn.prepareStatement("UPDATE employee SET salary=?,birthday=? WHERE name=?"); pst.setDouble(1, emp.getSalary()); pst.setString(2, DateFormatter.stringToSqlDate(emp.getBday())); pst.setString(3, emp.getName()); pst.executeUpdate(); }catch (Exception e) { e.printStackTrace(); } } public void delete(String id){ try{ Connection conn = BaseConnection.getConnection(); PreparedStatement pst = conn.prepareStatement("DELETE FROM employee WHERE name=?"); pst.setString(1, id); pst.executeUpdate(); }catch (Exception e) { e.printStackTrace(); } } public EmployeeBean find(String id){ try{ Connection conn = BaseConnection.getConnection(); PreparedStatement pst = conn.prepareStatement("SELECT * FROM employee WHERE name=?"); pst.setString(1, id); ResultSet rs = pst.executeQuery(); EmployeeBean emp = new EmployeeBean(); if(rs.next()){ emp.setName(rs.getString(1)); emp.setSalary(rs.getDouble(2)); emp.setBday(DateFormatter.dateToString(rs.getDate(3))); } return emp; }catch (Exception e) { e.printStackTrace(); } return null; } public ArrayList findAll(){ try{ Connection conn = BaseConnection.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employee"); ArrayList emps = new ArrayList(); while(rs.next()){ EmployeeBean emp = new EmployeeBean(); emp.setName(rs.getString(1)); emp.setSalary(rs.getDouble(2)); emp.setBday(DateFormatter.dateToString(rs.getDate(3))); emps.add(emp); } return emps; }catch (Exception e) { // TODO: handle exception } return null; }
public static void main(String[] args) { EmployeeDAO dao = new EmployeeDAO(); EmployeeBean empbean = new EmployeeBean(); /*empbean.setName("Auro d'morgan"); empbean.setSalary(7000.0); empbean.setBday("21-12-2009"); dao.update(empbean);*/ empbean=dao.find("amit"); //dao.delete("Auro d'morgan"); System.out.println(empbean.getName()+" "+empbean.getSalary()+" "+empbean.getBday()); empbean.setSalary(1111); /*ArrayList emps= dao.findAll(); for(EmployeeBean emp :emps){ System.out.println(emp.getName()+" "+emp.getSalary()+" "+emp.getBday()); }*/ }}

Tuesday, November 24, 2009

String Constant Pool * * * * *

The JVM set a pool in the memory for string to make memory more efficient that is called string constant pool.
Whenever compiler found a String literal (i.e. "hello", "good morning") then it check the pool whether same String exists or not. If a match found then it will return the reference of it, otherwise it will create a new string in the pool.

String s1="hello"; // create one object in string constant pool

Can you guess? how many objects are created in the following statement...
String s2= new String("welcome");

it will create two objects - one in string constant pool, second one in normal memory.

public class Test{


public static void
main(String[] args) {
String s1="hello";
String s2="hello";
//both reference refer to same instance of String
System.out.println(s1==s2);

String s3=new String("hello");
//s3 refer to new instance of String
System.out.println(s3==s2);

//content of s3 and s2 are same
System.out.println(s3.equals(s2));

}
}

Thursday, September 24, 2009

Immutable Objects

In Java, there are several immutable classes like String, Integer and all wrapper classes.
Immutable objects are the objects which fields can not be modified.
So Immutable class does not have any setter methods.
When we are writing the class that generate immutable objects then we must provide only private and final fields and class should be final.

for example -

public class M {
int m;

public int getM() {
return m;
}

public void setM(int m) {
this.m = m;
}

public String toString() {
return ""+m;
}
}
------------
public final class IM {
final private int x;
final private int y;
final private M z;
IM(int x,int y, M z){
this.x=x;
this.y=y;
this.z=z;
}

public int getX() {
return x;
}
public int getY() {
return y;
}
public M getZ() {
return z;
}
public IM addCordinate(IM im){ // like concat() in String
M newM = new M();
newM.setM(this.z.getM()+im.z.getM());
return new IM(this.x+im.x,this.y+im.y, newM);
}
public String toString() {
return "x: "+x+", y: "+y+", z: "+z;
}

}
------------
public class TestImmutability {
public static void main(String[] args) {
M m=new M();
m.setM(3);
IM im=new IM(1,2,m);
System.out.println(im);
M m1=new M();
m1.setM(1);
IM im1 = new IM(3,2,m1); // never share mutable fileds like - new IM(3,2,m) ,m already used
System.out.println(im.addCordinate(im1));// im.addCordinate(im1) returns a new one object.
}
}


for further help - Immutable Objects