Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Notes

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 14

OOPs Concepts

Data abstraction
Data abstraction refers to, providing only essential features by hiding its background details.
Real world example: Index of text book

Example: }
class result main()
{ {
int marks; bank b1;
float percentage; b1.input();
char name[20]; b1.output();
void input(); }
void output();

in the above example, b1 is an object calling input and output member functions, but that code is invisible to the object
b1."Abstraction" means its dictionary definition, which is probably "replace a complex topic with a simple name, as a
convenient reference."

Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.

Compile time – Method overloading

Overloaded methods are methods with the same name signature but either a different number of parameters or different types
in the parameter list. For example 'spinning' a number may mean increase it, 'spinning' an image may mean rotate it by 90
degrees. By defining a method for handling each type of parameter you achieve the effect that you want.

Class Book {
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}

Run time – Method overriding

Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the
subclass definition is used.

Class Tool {
void operate_it(){
}
}
Class ScrewDriver extends Tool {
void operate_it(){
}
}
Encapsulation

Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through a
public interface. For this, we need to declare the instance variables of the class as private or protected.The client code
should access only the public methods rather than accessing the data directly. Also, the methods should follow the Java
Bean's naming convention of set and get. Encapsulation makes it easy to maintain and modify code. The client code is not
affected when the internal implementation of the code changes as long as the public method signatures are unchanged.
For instance:

public class Employee


{
private float salary;
public float getSalary()
{
return salary;
}
public void setSalary(float salary)
{
this.salary = salary;
}

Inheritance
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem
bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each
also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road
bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this
example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming
language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited
number of subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed
by the name of the class to inherit from:

class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features
that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document
the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

Interface
As you've already learned, objects define their interaction with the outside world through the methods that they expose.
Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are
the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to
turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified
as an interface, might appear as follows:

interface Bicycle {
void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);


}
To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the
implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form
a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your
class claims to implement an interface, all methods defined by that interface must appear in its source code before the
class will successfully compile.

Note: To actually compile the ACMEBicycle class, you'll need to add the public keyword to the beginning of the implemented
interface methods. You'll learn the reasons for this later in the lessons on Classes and Objects and Interfaces and
Inheritance.

Abstract Methods and Classes


An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot
be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon),
like this:

abstract void moveTo(double deltaX, double deltaY);


If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent
class. However, if it does not, the subclass must also be declared abstract.

Note: All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used
with interface methods (it could be—it's just not necessary).

An Abstract Class Example


In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic
objects. These objects all have certain states (for example: position, orientation, line color, fill color) and behaviors (for
example: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic
objects—for example: position, fill color, and moveTo. Others require different implementations—for example, resize or
draw. All GraphicObjects must know how to draw or resize themselves; they just differ in how they do it. This is a perfect
situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit
from the same abstract parent object—for example, GraphicObject, as shown in the following figure.
First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all
subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for
methods, such as draw or resize, that need to be implemented by all subclasses but must be implemented in different
ways. The GraphicObject class can look something like this:

abstract class GraphicObject {


int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and
resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

When an Abstract Class Implements an Interface


In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface's
methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the
class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}

class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

String & String Buffer

String is an class and its objects are constt.String Buffer is anotehr class and is better than string since it saves time and
memory. String buffer includes all functions of string class also it has one more fn i.e sb.reverse();

1.String is immutable -- StringBuffer is not.

2. String is not thread safe -- StringBuffer is thread safe

3. String has concat() for append character -- StringBuffer has append() method
4. while you create String like String str new String(); --> it create 2 object 1 on heap and 1 on String Constant pool and that
referred by str --- That's not in StringBuffer it Create 1 object on heap

5. String is most commonly use in java applications ---- Mostly used in I/O functions.

What is the Vector class


The Vector class provides the capability to implement a growable array of objects . A vector implements dynamic array, which
can grow and shrink dynamically. It is similar to Arraylist with a difference that vector can be synchronized. it also
contain some legacy methods. ...

Synchronized Methods
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized
statements. The more complex of the two, synchronized statements, are described in the next section. This section is about
synchronized methods.

To make a method synchronized, simply add the synchronized keyword to its declaration:

public class SynchronizedCounter {


private int c = 0;

public synchronized void increment() {


c++;
}

public synchronized void decrement() {


c--;
}

public synchronized int value() {


return c;
}
}
If count is an instance of Synchronized Counter, then making these methods synchronized has two effects:
 First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is
executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object
block (suspend execution) until the first thread is done with the object.
 Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent
invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible
to all threads.

The advantages of synchronization would be manifested only during multithreading because synchronization means that
the resource which is synchronized can be used only by one thread at a time and NOT THAT ONLYONE THREAD
CAN RUN AT A TIME. Synchronization is necessary because there are some scenarios where in you need to prevent
interference when some activity is being done. eg: prevent modification of a file when it is being read etc. You can use as
many threads as you like even when you have synchronized some source because at the end of the day all the threads
would be able to access the resource only clause being they cannot access it at one point of time.

Note: that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.
Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it
while it is being constructed.

Interface Vs Abstract Class


When To Use Interfaces
An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code
whose original or primary purpose was quite different from your interface. To them, your interface is only incidental,
something that have to add on to the their code to be able to use your package.

When To Use Abstract classes


An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools
useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly
inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy
independently. In Java, a class can inherit from only one base class.

When to Use Both


You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they
choose. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them
via their abstract class name.

Summary Table
Interfaces vs Abstract Classes
Feature interface abstract class
Multiple
A class may implement several interfaces. A class may extend only one abstract class.
Inheritance
Default
An interface cannot provide any code at all, much
An abstract class can provide complete code, default
Implement
less default code. code, and/or just stubs that have to be overridden.
ation
Static final constants only, can use them without
qualification in classes that implement the
interface. On the other paw, these unqualified
Both instance and static constants are possible. Both static
Constants names pollute the namespace. You can use and instance intialiser code are also possible to
them and it is not obvious where they are compute the constants.
coming from since the qualification is
optional.
Third Party
An interface implementation may be added to A anythird party class must be rewritten to extend only from
Convenienc
existing third party class. the abstract class.
e
An abstract class defines the core identity of its
descendants. If you defined a Dog abstract class
then Dalmatian descendants are Dogs, they are not
merely dogable. Implemented interfaces enumerate
the general things a class can do, not the things a
class is.

Interfaces are often used to describe the peripheral


In a Java context, users should typically implement the
abilities of a class, not its central identity, Runnable interface rather than extending Thread,
is-a vs -able or
e.g. an Automobile class might implement because they’re not really interested in providing
can-do
the Recyclable interface, which could apply some new Thread functionality, they normally just
to many otherwise totally unrelated objects. want some code to have the capability of running
independently. They want to create something that
can be run in a thread, not a new kind of thread.The
similar is-a vs has-a debate comes up when you
decide to inherit or delegate.

multiple inheritance for further discussion of is-a vs has-


a
Plug-in You can write a new replacement module forYou an must use the abstract class as-is for the code base,
interface that contains not one stick of code with all its attendant baggage, good or bad. The
in common with the existing abstract class author has imposed structure on you.
Interfaces vs Abstract Classes
Feature interface abstract class
implementations. When you implement the
interface, you start from scratch without any
default implementation. You have to obtain
Depending on the cleverness of the author of the
your tools from other classes; nothing comes
abstract class, this may be good or bad.
with the interface other than a few constants.
This gives you freedom to implement a
radically different internal design.
If the various implementations are all of a kind and share
a common status and behaviour, usually an abstract
class works best. Another issue that’s important is
what I call "heterogeneous vs. homogeneous." If
implementors/subclasses are homogeneous, tend
If all the various implementations share is the towards an abstract base class. If they are
Homogeneity method signatures, then an interface works heterogeneous, use an interface. (Now all I have to
best. do is come up with a good definition of
hetero/homo-geneous in this context.) If the various
objects are all of-a-kind, and share a common state
and behavior, then tend towards a common base
class. If all they share is a set of method signatures,
then tend towards an interface.
If your client code talks only in terms ofJust an like an interface, if your client code talks only in
interface, you can easily change the concrete terms of an abstract class, you can easily change the
Maintenance
implementation behind it, using a factory concrete implementation behind it, using a factory
method. method.
Slow, requires extra indirection to find the
corresponding method in the actual class.
Speed Fast
Modern JVMs are discovering ways to
reduce this speed penalty.
The constant declarations in an interface areYou all can put shared code into an abstract class, where you
presumed public static final, so you may cannot into an interface. If interfaces want to share
leave that part out. You can’t call any code, you will have to write other bubblegum to
Terseness methods to compute the initial values of your arrange that. You may use methods to compute the
constants. You need not declare individual initial values of your constants and variables, both
methods of an interface abstract. They are all instance and static. You must declare all the
presumed so. individual methods of an abstract class abstract.
If you add a new method to an interface, you must
If you add a new method to an abstract class, you have the
Adding track down all implementations of that
option of providing a default implementation of it.
Functionali interface in the universe and provide them
Then all existing code will continue to work without
ty with a concrete implementation of that
change.
method.

What Is a Servlet?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via
a request-response programming model. Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific
servlet classes.

Serialization

Serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium
(such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is
reread according to the serialization format, it can be used to create a semantically identical clone of the original object.
For many complex objects, such as those that make extensive use of references, this process is not straightforward.
This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a
data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Threads vs. Processes

Thread: What do a t-shirt and a computer program have in common? They are both composed of many threads! While the
threads in a t-shirt hold the shirt together, the threads of a computer program alllow the program to execute sequential
actions or many actions at once. Each thread in a program identifies a process that runs when the program asks it to
(unlike when you ask your roommate to do the dishes).

Both threads and processes are methods of parallelizing an application. However, processes are independent execution units
that contain their own state information, use their own address spaces, and only interact with each other via interprocess
communication mechanisms (generally managed by the operating system). Applications are typically divided into
processes during the design phase, and a master process explicitly spawns sub-processes when it makes sense to logically
separate significant application functionality. Processes, in other words, are an architectural construct.

By contrast, a thread is a coding construct that doesn't affect the architecture of an application. A single process might
contains multiple threads; all threads within a process share the same state and same memory space, and can communicate
with each other directly, because they share the same variables.

Threads typically are spawned for a short-term benefit that is usually visualized as a serial task, but which doesn't have to
be performed in a linear manner (such as performing a complex mathematical computation using parallelism, or
initializing a large matrix), and then are absorbed when no longer required. The scope of a thread is within a specific code
module—which is why we can bolt-on threading without affecting the broader application.

Cookie
A cookie is information that a Web site puts on your hard disk so that it can remember something about you at a later
time. (More technically, it is information for future use that is stored by the server on the client side of a client/server
communication.) Typically, a cookie records your preferences when using a particular site. Using the Web's Hypertext
Transfer Protocol (HTTP), each request for a Web page is independent of all other requests. For this reason, the Web
page server has no memory of what pages it has sent to a user previously or anything about your previous visits.

A cookie is a mechanism that allows the server to store its own information about a user on the user's own computer. You
can view the cookies that have been stored on your hard disk (although the content stored in each cookie may not make
much sense to you). The location of the cookies depends on the browser. Internet Explorer stores each cookie as a
separate file under a Windows subdirectory. Netscape stores all cookies in a single cookies.txt fle. Opera stores them in a
single cookies.dat file.

Cookies are commonly used to rotate the banner ads that a site sends so that it doesn't keep sending the same ad as it sends
you a succession of requested pages. They can also be used to customize pages for you based on your browser type or
other information you may have provided the Web site. Web users must agree to let cookies be saved for them, but, in
general, it helps Web sites to serve users better.

String username=request.getParameter("username");
if(username==null) username="";
Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
JSP Life Cycle
1. JSP Page Translation:

A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the
translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets
the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.Note: The translation of a JSP source page into its
implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the
receipt and processing of a client request for the target JSP page.

3. Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:

In the execution phase the container manages one or more instances of this class in response to requests and other events.
The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface
HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation.
Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects.
_jspService() cannot be overridden.

7. jspDestroy() execution:

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven
(garbage collection). This is the end of jsp life cycle. jspInit(), _jspService() and jspDestroy() are called the life cycle
methods of the JSP.

Join queries

mysql> select * from demo_people;

+------------+--------------+------+

| name | phone | pid |

+------------+--------------+------+

| Mr Brown | 01225 708225 | 1|

| Miss Smith | 01225 899360 | 2|


| Mr Pullen | 01380 724040 | 3|

+------------+--------------+------+

3 rows in set (0.00 sec)

mysql> select * from demo_property;

+------+------+----------------------+

| pid | spid | selling |

+------+------+----------------------+

| 1| 1 | Old House Farm |

| 3| 2 | The Willows |

| 3| 3 | Tall Trees |

| 3| 4 | The Melksham Florist |

| 4| 5 | Dun Roamin |

+------+------+----------------------+

5 rows in set (0.00 sec)

If I do a regular JOIN (with none of the keywords INNER, OUTER, LEFT or RIGHT), then I get all records that
match in the appropriate way in the two tables, and records in both incoming tables that do not match are not reported:

mysql> select name, phone, selling from demo_people join demo_property on demo_people.pid = demo_property.pid;

+-----------+--------------+----------------------+

| name | phone | selling |

+-----------+--------------+----------------------+

| Mr Brown | 01225 708225 | Old House Farm |

| Mr Pullen | 01380 724040 | The Willows |

| Mr Pullen | 01380 724040 | Tall Trees |

| Mr Pullen | 01380 724040 | The Melksham Florist |

+-----------+--------------+----------------------+
4 rows in set (0.01 sec)
If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get an extra record for
each unmatched record in the left table of the join - thus ensuring (in my example) that every PERSON gets a mention:

mysql> select name, phone, selling from demo_people left join demo_property on demo_people.pid = demo_property.pid;
+------------+--------------+----------------------+

| name | phone | selling |

+------------+--------------+----------------------+

| Mr Brown | 01225 708225 | Old House Farm |

| Miss Smith | 01225 899360 | NULL |

| Mr Pullen | 01380 724040 | The Willows |

| Mr Pullen | 01380 724040 | Tall Trees |

| Mr Pullen | 01380 724040 | The Melksham Florist |

+------------+--------------+----------------------+

5 rows in set (0.00 sec)

If I do a RIGHT JOIN, I get all the records that match and IN ADDITION I get an extra record for each unmatched record
in the right table of the join - in my example, that means that each property gets a mention even if we don't have seller
details:

mysql> select name, phone, selling from demo_people right join demo_property on demo_people.pid = demo_property.pid;

+-----------+--------------+----------------------+

| name | phone | selling |

+-----------+--------------+----------------------+

| Mr Brown | 01225 708225 | Old House Farm |

| Mr Pullen | 01380 724040 | The Willows |

| Mr Pullen | 01380 724040 | Tall Trees |

| Mr Pullen | 01380 724040 | The Melksham Florist |

| NULL | NULL | Dun Roamin |

+-----------+--------------+----------------------+

5 rows in set (0.00 sec)

Forward :

When forward is used server forwards the request to the new url and the control stays on the same page. in other words it
just forward the request to new url and come back from where forward is called. When you use forward it will forward to
particular page but in browser forwarded url won't display
<jsp:forward page http://162.1.1.0/error.html) />

In browser u will see same url but it is the error.html page


sendRedirect :

sendRedirect forward the request to url as new request and the cotrol goes to the destination page and never come back to
the calling page. when you use send redirect it will rediredct the url to new url
and It will be displayed in browser
EX:
suppose u are in the page
http://162.0.0.1/submit.jsp and u r redircting url

response.sendRedirect(http://162.1.1.0/error.html);

then in browser url will changed and u will see error.html

Differences between <bean:message> and <bean:write>


<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that
can be substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>

<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>

Vector

 Vector is thread safe, because vector objects are synchronized which means you can access vector objects from any
number of threads at the same time without affecting its data.
 Due to the above reason, In performance wise Vector is slightly slower than ArrayList

ArrayList

 ArrayList is just opposite of Vector class. Its not thread safe, suppose if you are using ArrayList instances in multiple
threads surely which leads to create some problems while accessing.
 ArrayList comes from Collection Framework family. So its easy to developers to convert in to any other datastructure
formats.

Static variable

public class Static {


static int a=20;
int b=20;
public void inc() {
++a;
++b;
}
public static void main(String args[]) {
Static s=new Static();
s.inc();
System.out.print(s.a+" "+s.b+"\n");
Static t=new Static();
t.inc();
System.out.print(t.a+" "+t.b+"\n");
Static u=new Static();
u.inc();
System.out.print(u.a+" "+u.b+"\n");
}

}
Output
a b
21 21
22 21
23 21

Hash Map Vs Hash Table


1. Hashtable is synchronised but HashMap is not.
2. Hashtable does not allow "null" key but HashMap allows
"null" Key.

JDBC

JDBC Drivers Types

1. Type 1: JDBC-ODBC Bridge Driver


The first type of JDBC dirver is JDBC-ODBC Bridge which provide JDBC access to any ODBC complaint databases
through ODBC drivers. Sun's JDBC-ODBC bridge is example of type 1 driver.
2. Type 2: Native -API Partly - Java Driver
Type 2 drivers are developed using native code libraries, which were originally designed for accessing the database
through C/C++. Here a thin code of Java wrap around the native code and converts JDBC commands to DBMS-specific
native calls.
3. Type 3: JDBC-Net Pure Java Driver
Type 3 drivers are a three-tier solutions. This type of driver communicates to a middleware component which in turn
connects to database and provide database connectivity.
4. Type 4: Native-Protocol Pure Java Driver
Type 4 drivers are entirely written in Java that communicate directly with vendor's database through socket connection.
Here no translation or middleware layer, are required which improves performance tremendously.

Calling stored procedure

Here we present a stored procedure fetchuser(int userid) taht takes user id as parameter and returns the first_name and
last_name column
of the user.

try {
CallableStatement callablestmt = con.prepareCall("{call fetchuser(?)}");
callablestmt.setInt(1,1);
ResultSet rs1 = callablestmt.executeQuery();
while(rs1.next())
{
String fname = rs1.getString("FIRST_NAME");
String lname = rs1.getString("LAST_NAME");
out.println(fname+" "+lname+ "<br />");
}

} catch (SQLException e) {
e.printStackTrace();
}

Running simple query


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:odbc:dumy"; "sa", ""); // jdbc:mysql://<Server>:3306/<DB>

Statement Vs PreparedStatement

Statement – the statement is sent to the database server each and every time.
PreparedStatement – the statement is cached and then the execution path is pre determined on the database server allowing it
to be executed multiple times in an efficient manner.
However, there is a large speed difference with the first 50-60 records being sent. If you are doing less that 50-60 iterations of
this query it is still faster to use Statements rather than a PreparedStatement. However, it is twice as fast to use
PreparedStatements once you have iterated through it about 1000 times.

Class.forName(“driver”)
Class.forname method simply loads the class using the JVM's bootstrap class loader. If this class is a jdbc driver class then the
driver upon loading registers itself using DriverManager.registerDriver method. When DriverManager.getConnection is
called then the driver class corresponding to the connection URL is called. This is all managed by the DriverManager.

Critical Section Problem


Whenever two processes/threads are reading and writing the same variables in a language with SharedStateConcurrency, it is
possible that one process will interfere with the other (a RaceCondition).
For example, suppose that both processes are trying to increment the same variable. They both have the line
x := x + 1
in them. One way for each process to execute this statement is for it to read the variable, then add one to the value, then write it
back. Suppose the value of x was 3. If both processes read x at the same time then they would get the same value 3. If
they then both added 1 to it then they would both have the value 4. They would then both write 4 back to x. The result is
that both processes incremented x, but its value is only 4, instead of 5.
For these processes to execute properly, they must ensure that only one of them is executing the statement at a time. A set of
statements that can have only one process executing it at a time is a critical section. Another way of saying this is that
processes need mutually exclusive access to the critical section.
There are several ways to implement a critical section. If you have a single processor running all the processes that might enter
the critical section, you can DisableInterrupts? while a process is in the critical section. If you have multiple processors
and the critical section doesn't take long to execute, you should use BusyWaiting. If the critical section is long or if you
might have interrupts during the critical section then you should use SemaphoresForMutualExclusion. If you are very
clever then you might be able to think up an AlternativeToCriticalSection?.

You might also like