java all notes
TRANSCRIPT
Introduction
Java is a High Level programming Language.
The first name of Java was Oak, developed by a team led by James Gosling and Patrick Naughton
at Sun Microsystems in 1991. In 1995, it was renamed as Java.
In 1994, Java was used to develop a Web browser, named HotJava.
The browser able to download and run small Java programs over the internet, known as the
applets.
Capable to display animation and interact with the user.
In 1995, Netscape incorporated Java technology into its Netscape browser.
Then, other Internet companies followed . . .
A two‐step Java translation process have been developed:
Programs written in Java were translated into an intermediate language, known the byte
code.
Then, the byte code would be translated into machine language.
Difference between C++ and java
Characteristics of Java
Java is simple
Java is object-oriented
Java is distributed
Java is interpreted
Java is robust
Java is architecture-neutral
Java is portable
Java is multithreaded
Java is dynamic
Java is secure
Java Environment
Java includes many development tools, classes and methods
Development tools are part of Java Development Kit (JDK) and
The classes and methods are part of Java Standard Library (JSL), also known as
Application Programming Interface (API).
JDK constitutes of tools like java compiler, java interpreter and many.
API includes hundreds of classes and methods grouped into several packages according to their
functionality.
Java is architecture-neutral
WORA (Write Once Run Anywhere)
Java Capabilities
Java is a full‐featured and general‐purpose programming language that is capable of developing
a robust mission‐critical applications for: Desktops
Servers
Mobile devices
The Java programming language is a relatively high level language, class‐based and object‐oriented.
Java running on the desktop is called application.
Java running on the Internet is called applets.
Java developed on the server‐side is called servlet.
Java API
There are 3 editions of the Java API:
1. Java 2 standard edition (J2SE)
Client‐side standalone applications or applets.
2. Java 2 Enterprise Edition (J2EE)
Server‐side applications, such as Java servlets and Java Server Pages.
3. Java 2 Micro Edition (J2ME)
Mobile devices, such as cell phones or pda.
Portability
Portable means that a program may be written on one type of computer and then run on a wide
variety of computers, with little or no modification.
Java byte code runs on the JVM and not on any particular CPU; therefore, compiled Java programs
are highly portable.
JVMs exist on many platforms:
Windows
Macintosh
Linux
Basic object oriented concepts
Object Oriented Programming (OOP) is a programming concept used in several modern
programming languages, like C++, Java and Python.
Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java
supports the following fundamental concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
Objects
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
An object has three characteristics:
State: represents data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the
external user. But, it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Inheritance
Inheritance provides a powerful and natural mechanism for organizing and structuring your
software. This section explains how classes inherit state and behavior from their superclass’s, and
explains how to derive one class from another using the simple syntax provided by the Java
programming language.
Variable
A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable's memory; the range
of values that can be stored within that memory; and the set of operations that can be applied to
the variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println method, for example, the system actually executes several
statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, overload methods using the same names, and apply method
abstraction in the program design.
Creating Method: Considering the following example to explain the syntax of a method:
public static int funcName(int a, int b) {
// body
}
Advantage of Method
Code Reusability
Code Optimization
Java data types
Name Size Range Notes
boolean 1 true or false like C++'s bool, but it can't be assigned with a number
char 16 0 to 65535 This is bigger than C's char. This is because Java strings are Unicode, not ASCII. It's also unsigned by default.
byte 8 -128 to 127 Standard issue 'byte'
short 16 -32768 to 32767 just like a char, but signed by default
int 32 -2147483648 to 2147483647 standard-issue integer number type
long 64 -9223372036854775808 to 9223372036854775807
For very huge integers
float 32 +/- 1.4023x10-45 to 3.4028x10+38
general purpose real-number
double 64 +/- 4.9406x10-324 to 1.7977x10308
higher-precision real number
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case. If several words are
used to form a name of the class, each inner word's first letter should be in Upper Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several words are
used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example public void myMethodName()
Program File Name - Name of the program file should exactly match the class name. When
saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do not match your program
will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program processing starts from the main() method
which is a mandatory part of every Java program..
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
One can easily determine that these types are related.
One knows where to find types that can provide task-related functions.
The names of your types won't conflict with the type names in other packages because the
package creates a new namespace.
One can allow types within the package to have unrestricted access to one another yet still
restrict access for types outside the package.
Creating packages (Syntax of packages)
When creating a package, you should choose a name for the package and put a package statement
with that name at the top of every source file that contains the classes, interfaces, enumerations,
and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel(); }
What is the default package?
The default package is an unnamed package. The unnamed package contains java classes whose
source files did not contain a package declaration. The purpose of default package is for
convenience when developing small or temporary applications or when just beginning
development. The compiled class files will be in the current working directory.
A compilation unit that has no package declaration is part of an unnamed package.
Note that an unnamed package cannot have sub packages, since the syntax of a package declaration
always includes a reference to a named top level package.
Example
Built-in Package:-Existing Java package for example java.lang, java.util
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and multiple
inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why we use Interface:
This is one of the key features of interfaces.
The method to be executed is looked up dynamically at run time, allowing classes to be created
later than the code which calls methods on them.
The calling code can dispatch through an interface without having to know anything about the
"callee
Advantages Interfaces are mainly used to provide polymorphic behavior.
Interfaces function to break up the complex designs and clear the dependencies between objects.
Disadvantages Java interfaces are slower and more limited than other ones.
Interface should be used multiple number of times else there is hardly any use of having them.
Syntax: interface interface_name {}
Example of Interface interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Exception Handling in Java
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories
of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or
a problem that cannot be foreseen by the programmer. For example, if a file is to be opened,
but the file cannot be found, an exception occurs. These exceptions cannot simply be
ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Difference between exception and error in java
Both Error and Exception are derived from java.lang. Throw able in Java but main difference
between Error and Exception is kind of error they represent. java.lang. Error represent errors which
are generally cannot be handled and usually refer catastrophic failure e.g. running out of System
resources, some examples of Error in Java are
java.lang.OutOfMemoryError orJava.lang.NoClassDefFoundError and java.lang.UnSupportedCl
assVersionError. On the other hand java.lang .Exception represent errors which can be catch and
dealt e.g. IOException which comes while performing I/O operations i.e. reading files and
directories. Clear understanding of Error and Exception is must for any serious Java programmer
and good programming and debugging skills are required to overcome issues which caused Error
and Exception in Java. Apart from its must have knowledge in Java application
development, difference between Error and Exception is also a popular questions on Java
interviews related to Exception handling, similar to difference between throw and throws in Java.
In this Java article we will briefly see major difference between Error and Exception in Java which
include both syntactical and logical difference
Error vs Exception in Java
Here is my list of notable difference between Error vs Exception in Java.
1) As I said earlier, Main difference on Error vs Exception is that Error is not meant to catch as
even if you catch it you can not recover from it. For example during OutOfMemoryError, if you
catch it you will get it again because GC may not be able to free memory in first place. On the
other hand Exception can be caught and handled properly.
2) Error are often fatal in nature and recovery from Error is not possible which is different in case
of Exception which may not be fatal in all cases.
3) Unlike Error, Exception is generally divided into two categories e.g.checked and unchecked
Exceptions. Checked Exception has special place in Java programming language and require a
mandatory try catch finally code block to handle it. On the other hand Unchecked Exception, which
are subclass of RuntimeException mostly represent programming errors. Most common example
of unchecked exception is NullPointerException in Java.
4) Similar to unchecked Exception, Error in Java are also unchecked. Compiler will not throw
compile time error if it doesn't see Error handled with try catch or finally block. In fact handling
Error is not a good Idea because recovery from Error is mostly not possible.
That's all on difference between Error and Exception in Java. key point to remember is that Error
are fatal in nature and recovery may not be possible, on the other hand by carefully handling
Exception you can make your code more robust and guard against different scenarios.
Multiple Exceptions in Java 7
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This
is also known as multi catch.
Before Java 7 you would write something like this: try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException e) {
logger.log(e);
} catch(IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
As you can see, the two exceptions SQLException and IOException are handled in the same way,
but you still have to write two individual catch blocks for them.
In Java 7 you can catch multiple exceptions using the multi catch syntax: try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Notice how the two exception class names in the first catch block are separated by the pipe
character |. The pipe character between exception class names is how you declare multiple
exceptions to be caught by the same catch clause.
Finally clause
Finally clause is executed even when exception is thrown from anywhere in try/catch block.
Because it's the last to be executed in the main and it throws an exception, that's the exception that
the callers see.
Hence the importance of making sure that the finally clause does not throw anything, because it
can swallow exceptions from the try block.
The addition of the finally clause is great convenience in certain situations. It allows cleanup kinds
of actions to take place regardless of how a compound statement terminated.
OR
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred. Using a finally block allows you
to run any cleanup-type statements that you want to execute, no matter what happens in the
protected code. A finally block appears at the end of the catch blocks and has the following syntax: try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
The throws clause
The throws clause is used when we know that a method may cause exceptions, but the method
does not handle those exceptions.
In such a case, a user has to throw those exceptions to the caller of the method by using the throws
clause.
A throws clause is used when a method is declared.
A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException: import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{ // Method implementation
}
//Remainder of class definition}
The throw clause
Till now, we have learned about catching exceptions thrown by JRE.
In this section, we will learn to throw exceptions explicitly i.e. custom exception.
We can throw an object of any exception type in Java by using the new operator with throw clause.
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature. You can throw an
exception, either a newly instantiated one or an exception that you just caught, by using the throw
keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException: import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
When Using Exceptions
Exception handling separates error-handling code from normal programming tasks, thus making
programs easier to read and to modify. Be aware, however, that exception handling usually
requires more time and resources because it requires instantiating a new exception object, rolling
back the call stack, and propagating the errors to the calling methods
When not to Using Exceptions
Don’t use exceptions for your normal application flow. Take a look at the following
There are multiple reasons why you should not do this:
1. Exceptions are not designed for this. Developers using this API or reading through the
source code will be confused. It looks like a failure scenario but it’s just some sort of flow
control.
2. Exceptions are hard to follow. If you are using exceptions like this, you are using just
another form of a goto statement. I don’t have to clarify why using goto is a bad idea,
do I?
3. Exceptional exceptions? If you use exceptions for normal situations, how do you signal
unusual situations?
4. Exceptions are slow. Because exception only rarely occur, performance is not a priority for
the implementers of compilers nor the designers of the language. Throwing and catching
exceptions is inefficient and many times slower than a simple check of a return value or a
state field.
Don’t use exceptions to signal something completely normal. Don’t use exceptions to control your
normal application flow. Use return values or state fields for flow control instead.
Multitasking
When the CPU performs multiple (more than one) tasks at the same time then the technique is
called multitasking.
There are two distinct types of multitasking:
1. process-based
2. thread-based
Process-based Multitasking
A process is a program that is executing. Thus, process-based multitasking is the feature that
allows your computer to run two or more programs concurrently. For example, process-based
multitasking enables you to run the Java compiler at the same time that you are using a text editor.
In process-based multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
Thread-based Multitasking
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
This means that a single program can perform two or more tasks simultaneously. For instance, a
text editor can format text at the same time that it is printing, as long as these two actions are being
performed by two separate threads. Thus, process-based multitasking deals with the “big picture,”
and thread-based multitasking handles the details.
Multithreading
A multithreaded program contains two or more parts that can run concurrently. Each part of such
a program is called a thread, and each thread defines a separate path of execution. Java provides
built-in support for multithreaded programming.
Java - Multithreading
Java is amultithreaded programming language which means we can develop multithreaded
program using Java. A multithreaded program contains two or more parts that can run concurrently
and each part can handle different task at the same time making optimal use of the available
resources especially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such as
a CPU. Multithreading extends the idea of multitasking into applications where you can subdivide
specific operations within a single application into individual threads. Each of the threads can run
in parallel. The OS divides processing time not only among different applications, but also among
each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed concurrently
in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.
Above-mentioned stages are explained here:
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Thread Class Methods
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running
join Wait for a thread to terminate.
Run Entry point for the thread.
sleep Suspend a thread for a period of time.
Start Start a thread by calling its run method.
Java - Thread Control
Core Java provides a complete control over multithreaded program. You can develop a
multithreaded program which can be suspended, resumed or stopped completely based on your
requirements. There are various static methods which you can use on thread objects to control their
behavior. Following table lists down those methods:
SN Methods with Description
1 public void suspend()
This method puts a thread in suspended state and can be resumed using resume() method.
2 public void stop()
This method stops a thread completely.
3 public void resume()
This method resumes a thread which was suspended using suspend() method.
4 public void wait()
Causes the current thread to wait until another thread invokes the notify().
5 public void notify()
Wakes up a single thread that is waiting on this object's monitor.
Be aware that latest versions of Java has deprecated the usage of suspend(), resume(), and stop()
methods and so you need to use available alternatives.
How to make Thread in Java
There are two ways of implementing threading in Java
1) Create a class that extends the standard Thread class.( java.lang.Thread class)
2) Create a class that implements the standard Runnable interface(java.lang.Runnable )
That is, a thread can be defi ned by extending the java.lang.Thread class (see Fig. 14.3a) or
by implementing the java.lang.Runnable interface (see Fig. 14.3b). The run() method
should be overridden and should contain the code that will be executed by the new thread. This
method must be public with a void return type and should not take any arguments. Both threads
and processes are abstractions for 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).
Extending the Thread Class
The steps for creating a thread by using the fi rst mechanism are:
1. Create a class by extending the Thread class and override the run() method: class MyThread extends Thread {
public void run() {
// thread body of execution
}
}
2. Create a thread object: MyThread thr1 = new MyThread();
3. Start Execution of created thread: thr1.start();
An example program illustrating creation and invocation of a thread object is given below: Program 14.1
/* ThreadEx1.java: A simple program creating and invoking a thread object by
extending the standard Thread class. */
class MyThread extends Thread {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
The class MyThread extends the standard Thread class to gain thread properties through
inheritance.
The user needs to implement their logic associated with the thread in the run() method, which is
the body of thread. The objects created by instantiating the class MyThread are called threaded
objects. Even though the execution method of thread is called run, we do not need to explicitly
invoke this method directly.
When the start() method of a threaded object is invoked, it sets the concurrent execution of the
object from that point onward along with the execution of its parent thread/method.
Implementing the Runnable Interface
The steps for creating a thread by using the second mechanism are:
1. Create a class that implements the interface Runnable and override run() method: class MyThread implements Runnable {
…
public void run() {
// thread body of execution
}
}
2. Creating Object: MyThread myObject = new MyThread();
3. Creating Thread Object: Thread thr1 = new Thread(myObject);
4. Start Execution: thr1.start();
An example program illustrating creation and invocation of a thread object is given below: Program 14.2
/* ThreadEx2.java: A simple program creating and invoking a thread object by
implementing Runnable interface. */
class MyThread implements Runnable {
public void run() {
System.out.println(“ this thread is running ... ”);
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}
The class MyThread implements standard Runnable interface and overrides the run() method and
includes logic associated with the body of the thread (step 1). The objects created by instantiating
the class MyThread are normal objects (unlike the fi rst mechanism) (step 2). Therefore, we need
to create a generic Thread object and pass MyThread object as a parameter to this generic object
(step 3). As a result of this association, threaded object is created. In order to execute this threaded
object, we need to invoke its start() method which sets execution of the new thread (step 4).
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet? There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Java AWT Tutorial
Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources of system.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
Simple example of AWT by association import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Servlet
Servlet technology is used to create web application (resides at server side and generates dynamic
web page).
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or applications
on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Client-side vs. Server-side
Client-side means that the action takes place on the user’s (the client’s) computer. Server-side
means that the action takes place on a web server.
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In
most cases, the client is a web browser.
The User - The user uses the Client in order to surf the web, fill in forms, watch videos
online, etc.
Servlet Life Cycle
Loading Servlet Class : A Servlet class is loaded when first request for the servlet is
received by the Web Container.
Servlet instance creation :After the Servlet class is loaded, Web Container creates the
instance of it. Servlet instance is created only once in the life cycle.
Call to the init() method : init() method is called by the Web Container on servlet
instance to initialize the servlet.
Signature of init() method :
public void init(ServletConfig config) throws ServletException
Call to the service() method : The containers call the service() method each time the
request for servlet is received. The service() method will then call
the doGet() or doPost() methos based ont eh type of the HTTP request, as explained
in previous lessons.
Signature of service() method :
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
Call to destroy() method: The Web Container call the destroy() method before
removing servlet instance, giving it a chance for cleanup activity.