World's most popular travel blog for travel bloggers.

 Servlet: A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.

Servlet life cycle: A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet.

  • The servlet is initialized by calling the init() method.
  • The servlet calls service() method to process a client’s request.
  • The servlet is terminated by calling the destroy() method.
  • Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException {
   // Initialization code...

The service() Method

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response) 
   throws ServletException, IOException {

The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code

The destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −

public void destroy() {
   // Finalization code...

 The communication between the nodes in a packet data network must be precisely defined to ensure correct interpretation of the packets by the receiving intermediate and the end systems. The packets exchanged between nodes are defined by a protocol - or communications language.

There are many functions which may be need to be performed by a protocol. These range from the specification of connectors, addresses of the communications nodes, identification of interfaces, options, flow control, reliability, error reporting, synchronization, etc. In practice there are so many different functions, that a set (also known as suite or stack) of protocols are usually defined. Each protocol in the suite handles one specific aspect of the communication.

The protocols are usually structured together to form a layered design (also known as a "protocol stack"). All major telecommunication network architectures currently used or being developed use layered protocol architectures. The precise functions in each layer vary. In each case, however, there is a distinction between the functions of the lower (network) layers, which are primarily designed to provide a connection or path between users to hide details of underlying communications facilities, and the upper (or higher) layers, which ensure data exchanged are in correct and understandable form. The upper layers are sometimes known as "middleware" because they provide software in the computer which convert data between what the applications programs expect, and what the network can transport. The transport layer provides the connection between the upper (applications-oriented) layers and the lower (or network-oriented) layers.

The basic idea of a layered architecture is to divide the design into small pieces. Each layer adds to the services provided by the lower layers in such a manner that the highest layer is provided a full set of services to manage communications and run distributed applications. A basic principle is to ensure independence of layer by defining services provided by each layer to the next higher layer without defining how the services are to be performed. This permits changes in a layer without affecting other layers. Prior to the use of layered protocol architectures, simple changes such as adding one terminal type to the list of those supported by an architecture often required changes to essentially all communications software at a site.

Microwave: Electromagnetic Spectrum consists of entire range of electromagnetic radiation. Radiation is the energy that travels and spreads out as it propagates. The types of electromagnetic radiation that makes the electromagnetic spectrum is depicted in the following screenshot.

Properties of Microwaves

Following are the main properties of Microwaves.

  • Microwaves are the waves that radiate electromagnetic energy with shorter wavelength.
  • Microwaves are not reflected by Ionosphere.
  • Microwaves travel in a straight line and are reflected by the conducting surfaces.
  • Microwaves are easily attenuated within shorter distances.
  • Microwave currents can flow through a thin layer of a cable.
  • Supports larger bandwidth and hence more information is transmitted. For this reason, microwaves are used for point-to-point communications.
  • More antenna gain is possible.
  • Higher data rates are transmitted as the bandwidth is more.
  • Antenna size gets reduced, as the frequencies are higher.
  • Low power consumption as the signals are of higher frequencies.
  • Effect of fading gets reduced by using line of sight propagation.
  • Provides effective reflection area in the radar systems.
  • Satellite and terrestrial communications with high capacities are possible.
  • Low-cost miniature microwave components can be developed.
  • Effective spectrum usage with wide variety of applications in all available frequency ranges of operation.


String is slow and consumes more memory when you concat too many strings because every time it creates new instance.StringBuffer is fast and consumes less memory when you concat strings.
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.StringBuffer class doesn’t override the equals() method of Object class.

Q8. a) What is proxy server? Explain URL class and its methods in java.

Answer : – A proxy server is basically another computer which serves as a hub through which internet requests are processed. By connecting through one of these servers, your computer sends your requests to the server which then processes your request and returns what you were wanting. In this way it serves as an intermediary between your home machine and the rest of the computers on the internet.

Proxies are used for a number of reasons such as :

  • Control internet usage in corporate networks
  • Bandwidth savings for large networks
  • Monitoring and Filtering
  • Privacy (hide your IP address, location, and other information)
  • Security

Constructors of Java URL class

URL(String spec)
Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given context.

Commonly used methods of Java URL class

The class provides many methods. The important methods of URL class are given below.

public String getProtocol( )it returns the protocol of the URL.
public String getHost( )it returns the host name of the URL.
public String getPort( )it returns the Port Number of the URL.
public String getFile( )it returns the file name of the URL.
public String getAuthority( )it returns the authority of the URL.
public String toString( )it returns the string representation of the URL.
public String getQuery( )it returns the query string of the URL.
public String getDefaultPort( )it returns the default port of the URL.
public URLConnection openConnection( )it returns the instance of URLConnection i.e. associated with this URL.
public Object getContent( )it returns the content of the URL.

Servlet can be described in many ways, depending on the context.

  • Servlet is a technology which is used to create a web application.
  • Servlet is an API that provides many interfaces and classes including documentation.
  • Servlet is an interface that must be implemented for creating any Servlet.
  • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
  • Servlet is a web component that is deployed on the server to create a dynamic web page.

GET Method

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation : only 1024 characters can be used in a request string.

This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet( ) method.

POST Method

A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost( ) method.

Servlets handles form data parsing automatically using the following methods depending on the situation −

  • getParameter( ) − You call request.getParameter( ) method to get the value of a form parameter.
  • getParameterValues( ) − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
  • getParameterNames( ) − Call this method if you want a complete list of all parameters in the current request.

 A socket programming interface provides the routines required for interprocess communication between applications, either on the local system or spread in a distributed, TCP/IP based network environment. Once a peer-to-peer connection is established, a socket descriptor is used to uniquely identify the connection. The socket descriptor itself is a task specific numerical value.

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.

On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server’s machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.

The client and server can now communicate by writing to or reading from their sockets.



·      Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.


·       Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","password");  

·      Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

Statement stmt=con.createStatement();  

·      Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

ResultSet rs=stmt.executeQuery("select * from emp");  



System.out.println(rs.getInt(1)+" "+rs.getString(2));  


5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.


 A Java package is a set of classes which are grouped together. This grouping helps to organize Java classes and interfaces classes with the same name.

  • A package provides a unique namespace for the types it contains.
  • Classes in the same package can access each other’s package-access members.

Creating package

package world;

public class HelloWorld {

  public static void main(String[] args) {

    System.out.println(“Hello World”);



Calling package

import world.*; 

import world.moon;

PATH: maintains a list of directories. The OS searches the PATH entries for executable programs, such as Java Compiler (javac) and Java Runtime (java).

CLASSPATH: maintain a list of directories (containing many Java class files) and JAR files (a single-file archive of Java classes). The Java Compiler and Java Runtime searches the CLASSPATH entries for Java classes referenced in your program.


  • Class and object

A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog would consist of traits shared by all dogs. A class is collection of the properties and methods are called members. Object is an instance of class.

Data abstraction: – it is a process that provides only essential features by hiding its background details. A data abstraction is a simple view of an object that includes required features and hides the unnecessary details.

  •  Data abstraction & Data encapsulation –

it is a process that provides only essential features by hiding its background details. A data abstraction is a simple view of an object that includes required features and hides the unnecessary details. it is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

  • Applet vs Application program

Java Application:

  • A java application is a stand-alone program. This means it can be run by itself.
  • It cannot access from web browser.
  • It is run by JVM.
  • It can access on local machine on which program is reside.


  • Applet cannot run as independent program.
  • Applet program can run from within a web browser or similar java enabled application such as an applet viewer
  • Java applets are included in HTML pages using <applet> tag.
  • Applet communicates with server only.
  • Applets are not allowed to read or write to files on the local system.

 Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.

Advantages of using a Package in Java

  • Reusability - While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.

  • Better Organization - Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.

  • Name Conflicts - We can define two classes with the same name in different packages so to avoid name collision, we can use packages.

There are 4 types of java access modifiers :

  • private - The private access modifier is accessible only within class.

  • default - If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

  • protected - The protected access modifier is accessible within package and outside the package but through inheritance only.

  • public - The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.


  • A static method belongs to the class rather than the object of a class.
  • A static method can be accessed directly by the class name and doesn’t need any object.
  • A static method can access static data member and can change the value of it.
  • A static method cannot refer to "this" or "super" keywords in anyway.

In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[ ]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.

 Layout Manager: The Layout managers enable us to control the way in which visual components are arranged in the GUI forms by determining the size and position of components within the containers.

Java – Flow Layout

Flow layout is the default layout, which means if you don’t set any layout in your code then layout would be set to Flow by default. Flow layout puts components (such as text fields, buttons, labels etc) in a row, if horizontal space is not enough to hold all components then Flow layout adds them in a next row and so on.

Example: Here is the image of a Frame where eight buttons have been added to a Frame under Flow layout. As you can see buttons 7 & 8 are in second row because first six buttons consumed all horizontal space.

Points to Note:

  • All rows in Flow layout are center aligned by default. As you can see in the above image that buttons 7 & 8 are in center. However we can set the alignment to left or right, we will learn about it later in this post.
  • The default horizontal and vertical gap between components is 5 pixels.
  • By default the components Orientation is left to right, which means the components would be added from left to right, however we can change it to right to left as well, we will see that later in this post.

Simple Flow Layout Example

The image shown above is the output of this code. Here we are adding 8 buttons to a Frame and layout is being set to FlowLayout.

import java.awt.*;
public class FlowLayoutDemo extends Frame{
    // constructor
    public FlowLayoutDemo(String title)
        /* It would create the Frame by calling
         * the constructor of Frame class.
        //Setting up Flow Layout
        setLayout(new FlowLayout());
        //Creating a button and adding it to the frame
        Button b1 = new Button("Button:1");
        /* Adding other components to the Frame
        Button b2 = new Button("Button:2");
        Button b3 = new Button("Button:3");
        Button b4 = new Button("Button:4");
        Button b5 = new Button("Button:5");
        Button b6 = new Button("Button:6");
        Button b7 = new Button("Button:7");
        Button b8 = new Button("Button:8");
    public static void main(String[] args)
    {   FlowLayoutDemo screen = 
            new FlowLayoutDemo("Flow Layout -");

Flow Layout where Orientation is right to left

The default Orientation for flow layout is left to right, however we can set it to right to left if want.

import java.awt.*;
public class FlowLayoutDemo extends Frame{
    // constructor
    public FlowLayoutDemo(String title)
        /* It would create the Frame by calling
         * the constructor of Frame class.
        //Setting up Flow Layout
        setLayout(new FlowLayout());
        //Creating a button and adding it to the frame
        Button b1 = new Button("Button:1");
        /* Adding other components to the Frame
        Button b2 = new Button("Button:2");
        Button b3 = new Button("Button:3");
        Button b4 = new Button("Button:4");
        Button b5 = new Button("Button:5");
        Button b6 = new Button("Button:6");
        Button b7 = new Button("Button:7");
        Button b8 = new Button("Button:8");
        /* This would set the Orientation to 
         *  RightToLeft
    public static void main(String[] args)
    {   FlowLayoutDemo screen = 
            new FlowLayoutDemo("Flow Layout -");

 Exception: When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Types of Exception in Java with Examples

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. 

  1. ArithmeticException 
    It is thrown when an exceptional condition has occurred in an arithmetic operation.
  2. ArrayIndexOutOfBoundsException 
    It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  3. ClassNotFoundException 
    This Exception is raised when we try to access a class whose definition is not found
  4. FileNotFoundException 
    This Exception is raised when a file is not accessible or does not open.
  5. IOException 
    It is thrown when an input-output operation failed or interrupted
  6. InterruptedException 
    It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
  7. NoSuchFieldException 
    It is thrown when a class does not contain the field (or variable) specified
  8. NoSuchMethodException 
    It is thrown when accessing a method which is not found.
  9. NullPointerException 
    This exception is raised when referring to the members of a null object. Null represents nothing
  10. NumberFormatException 
    This exception is raised when a method could not convert a string into a numeric format.
  11. RuntimeException 
    This represents any exception which occurs during runtime.
  12. StringIndexOutOfBoundsException 
    It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string

Exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly.

class Main {
public static void main(String[] args) {

try {

// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());


ArithmeticException => / by zero

 Polymorphism: Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.

Polymorphism in java programming

In Java polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism

1. Compile-time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. But Java doesn’t support the Operator Overloading.

Method Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.

2. Runtime Polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

Method Overriding , on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden

 Java final keyword

In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes.

Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,

  • the final variable cannot be reinitialized with another value
  • the final method cannot be overridden
  • the final class cannot be extended

1. Java final Variable

In Java, we cannot change the value of a final variable. For example,

class Main {
  public static void main(String[] args) {

    // create a final variable
    final int AGE = 32;

    // try to change the final variable
    AGE = 45;
    System.out.println("Age: " + AGE);

In the above program, we have created a final variable named age. And we have tried to change the value of the final variable.

When we run the program, we will get a compilation error with the following message.

cannot assign a value to final variable AGE
    AGE = 45;

 The prime reason behind creation of Java was to bring portability and security feature into a computer language. Beside these two major features, there were many other features that played an important role in moulding out the final form of this outstanding language. Those features are :

1) Simple

Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way.

Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.

2) Object Oriented

In java, everything is an object which has some data and behaviour. Java can be easily extended as it is based on Object Model. Following are some basic concept of OOP's.

  1. Object

  2. Class

  3. Inheritance

  4. Polymorphism

  5. Abstraction

  6. Encapsulation

3) Robust

Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime checking. But the main areas which Java improved were Memory Management and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.

4) Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere language.

On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on any machine, plus this bytecode format also provide security. Any machine with Java Runtime Environment can run Java Programs.

Java is platform Independent Language

5) Secure

When it comes to security, Java is always the first choice. With java secure features it enable us to develop virus free, temper free system. Java program always runs in Java runtime environment with almost null interaction with system OS, hence it is more secure.

6) Multi Threading

Java multithreading feature makes it possible to write program that can do many tasks simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads at the same time, like While typing, grammatical errors are checked along.

7) Architectural Neutral

Compiler generates bytecodes, which have nothing to do with a particular computer architecture, hence a Java program is easy to intrepret on any machine.

8) Portable

Java Byte code can be carried to any platform. No implementation dependent features. Everything related to storage is predefined, example: size of primitive data types

9) High Performance

Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java enables high performance with the use of just-in-time compiler.

10) Distributed

Java is also a distributed language. Programs can be designed to run on computer networks. Java has a special class library for communicating using TCP/IP protocols. Creating network connections is very much easy in Java as compared to C/C++.

New Features of JAVA 8

Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go through them quickly, we will explore them in details later.

  • Enhanced Productivity by providing Optional Classes feature, Lamda Expressions, Streams etc.

  • Ease of Use

  • Improved Polyglot programming. A Polyglot is a program or script, written in a form which is valid in multiple programming languages and it performs the same operations in multiple programming languages. So Java now supports such type of programming technique.

  • Improved Security and performance.

New Features of JAVA 11

Java 11 is a recommended LTS version of Java that includes various important features. These features includes new and upgrades in existing topic. Just go through them quickly, we will explore them in details later.

  • includes support for Unicode 10.0.0

  • The HTTP Client has been standarized

  • Lazy Allocation of Compiler Threads

  • Updated Locale Data to Unicode CLDR v33

  • JEP 331 Low-Overhead Heap Profiling

  • JEP 181 Nest-Based Access Control

  • Added Brainpool EC Support (RFC 5639)

  • Enhanced KeyStore Mechanisms

  • JEP 332 Transport Layer Security (TLS) 1.3

  • JEP 330 Launch Single-File Source-Code Programs