Java Notes
Java Notes
Java Notes
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.
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){
}
}
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:
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:
}
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);
}
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.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon),
like this:
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).
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 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();
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.
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:
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.
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.
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).
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.
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
+------------+--------------+------+
+------------+--------------+------+
+------------+--------------+------+
+------+------+----------------------+
+------+------+----------------------+
| 3| 2 | The Willows |
| 3| 3 | Tall Trees |
| 4| 5 | Dun Roamin |
+------+------+----------------------+
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;
+-----------+--------------+----------------------+
+-----------+--------------+----------------------+
+-----------+--------------+----------------------+
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;
+------------+--------------+----------------------+
+------------+--------------+----------------------+
+------------+--------------+----------------------+
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;
+-----------+--------------+----------------------+
+-----------+--------------+----------------------+
+-----------+--------------+----------------------+
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) />
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);
<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
}
Output
a b
21 21
22 21
23 21
JDBC
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();
}
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.