Write a program to sort object using comparable ?

Check this one also
Sort employee object in descending order
Here I am taking class Employee:

package com.instanceofjava;

import java.util.Comparable;
public class Employee implements Comparable<Employee> {
 int id;
 String name;
 public Employee(int id, String name) {
  this.id=id;
  this.name=name;
 }
  public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Override
 public int compareTo(Employee e) {
 Integer i= this.getId();
 Integer j=e.getId();
     if (this.getId() == e.getId())
       return 0;
      if (this.getId() < e.getId())
        return 1;
      if (this.getId() > e.getId())
       return -1;
      return 0;
 }

}

Here I am taking another class Main.Here I am adding objects to the My list

package com.oops;
import java.util.ArrayList;  
import java.util.Collections;
import java.util.Iterator;
import java.io.*;  
  
class Main{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
al.add(new Employee(101,"Indhu"));  
al.add(new Employee(106,"Sindhu"));  
al.add(new Employee(105,"Swathi"));  
  
Collections.sort(al);  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
Employee st=(Employee)itr.next();  
System.out.println(st.id +" "+st.name );  
  }  
}  
}  

Output:
Indhu
Swathi

Servlet Architecture


  • Servlets read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
  • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
  • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
  • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
  • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Servlet API:

  • Servelt API contains three packages 
  • javax.servlet: Package contains a number of classes and interfaces that describe the contract
    between a servlet class and the runtime environment provided for an instance of such a class a
    conforming servelt container.
  • javax.servlet.aanotation: Package contains a number of annotations that allow users to use
    annotations to declare servlets , filters, listeners and specify the metadata for the declared component
  • javax.servlet.http: Package contains a number of classes and interfaces that describe and define the contract between a servlet class rnning under the HTTP protocal and the runtime environment provided for an instance of such class by a confirming servlet container.

Interfaces present in javax.servlet:

  • AsyncContext
  • AsyncListener
  • Filter
  • FilterChain
  • FilterConfig
  • RequestDispatcher
  • Servlet
  • ServletConfig
  • ServletContext
  • ServletContextAttributeListener
  • ServletContextListener
  • ServletRequest
  • ServletRequestAttributeListener
  • ServletRequestListener
  • ServletResponse
  • SingleThreadModel

Classes present in javax.servlet:

  • AsyncEvent
  • ServletInputStream
  • ServletOutputStream
  • GenericServlet
  • ServletContextEvent
  • ServletContextAttributeEvent
  • ServletRequestAttributeEvent
  • ServeltRequestEvent
  • ServletRequestWrapper
  • ServeletResponseWrapper
  • SessionCookieConfig

Exceptions:

  • ServletException
  • UnavilableException

 Interfaces present in javax.servlet.http:  

  • HttpServletRequest 
  • HttpServletResponse
  • HttpSession
  • HttpSessionBindingListener
  • HttpSessionContext
  • HttpSessionListener
  • HttpSessionActivationListener
  • HttpSessionAttributeListener

Classes present in javax.servlet.http:

  • Cookie
  • HttpServlet
  • HttpServletRequestWrapper
  • HttpServletResponseWrapper
  • HttpSessionBindingEvent
  • HttpSessionEvent
  • HttpUtils

Annotation types declared in javax.servlet.annotation package

  • InitParam
  • ServletFilter
  • WebServlet
  • WebservletContextListener
Servlet







    write a program to create singleton class?






    Check this singleton design pattern explained with programs and steps

    public class Singleton {

    static Singleton obj;
    private  Singleton(){
    }

    public static Singleton getInstance(){
    if(obj!=null){
    return  obj;
    }
    else{
    obj=new Singleton();
    return obj;
    }
    }

    public static void main(String[] args) {

    Singleton obj=Singleton.getInstance();
    Singleton obj1=Singleton.getInstance();

    if(obj==obj1){
    System.out.println("indhu");
    }
    else{
    System.out.println("Sindhu");
    }
                   System.out.println(obj==obj1);

    }
    }


    Output:
    indhu
    true

    What is servlet

    • Servlet is a web technology from Sun microsystems(On January 27, 2010, Sun was acquired by Oracle Corporation)
    • Servlets is a Java based web technology to develop server side programs to make a website interactive.
    • Servlet is an API.
    • Servlet is aspecification.
    • Any java based interactive website can be loaded into any brand web servlet without changing the single line of source code as web server is developed according to servlet specification.
    • Servlet is a J2EE technology.

      Web container:

    • Web container is a software that comprises of three modules 
    1. web server
    2. Servlet Engine/ servlet container
    3. Jsp  Engine / Jsp container


    Servlet engine:

    • servlet  java engine is specialized software developed according to  specification
    • A jsp engine is a  specialized software developed according to  specification
    • jsp engine execute s jsps

    General duties of servlet:

    • To make website interactive a servlet performs the folowing duties in general
    1. Capturing the user input
    2. communicating with database
    3. processing of data
    4. producing a dynamic page
    5. Handling over the dynamic page to the webserver

    Swap two numbers in java example

    This is a Java program that illustrates situations where two numbers will be swapped.

    Explaining Different Swapping Methods: 

    Using a Temporary Variable
    • Store a number in a temporary variable.
    • Swap the values by assigning them correctly as follows exactly the same workmethod 
    Without a Temporary Variable (Using Arithmetic):
    • Adding and subtracting to swap in arithmetic
    • Risk: Possible overflow for large number if that number you see is right due to introduction extra space (for temporary variable)
    Using Bitwise XOR:
    • XOR is an efficient solution to swapping numbers.
    • Applies to int types
    Using a Single Statement:
    • use of arithmetic.
    • Single line swap, no extra variable required.

    Swap two numbers in Java example program 

    1. import java.util.Scanner;

    2. public class SwapNumbers {
    3.     
    4.     // Swap two numbers in java using a temporary variable
    5.     public static void swapWithTemp(int a, int b) {
    6.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    7.         int temp = a;
    8.         a = b;
    9.         b = temp;
    10.         System.out.println("After Swap: a = " + a + ", b = " + b);
    11.     }

    12.     // Swap two numbers without using a temporary variable (using arithmetic operations)
    13.     public static void swapWithoutTemp(int a, int b) {
    14.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    15.         a = a + b;
    16.         b = a - b;
    17.         a = a - b;
    18.         System.out.println("After Swap: a = " + a + ", b = " + b);
    19.     }
    20.     
    21.     // Swap two numbers using bitwise XOR operator
    22.     public static void swapWithXOR(int a, int b) {
    23.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    24.         a = a ^ b;
    25.         b = a ^ b;
    26.         a = a ^ b;
    27.         System.out.println("After Swap: a = " + a + ", b = " + b);
    28.     }

    29.     // Swap two numbers in java using a single statement (tuple swap)
    30.     public static void swapSingleStatement(int a, int b) {
    31.         System.out.println("Before Swap: a = " + a + ", b = " + b);
    32.         b = (a + b) - (a = b);
    33.         System.out.println("After Swap: a = " + a + ", b = " + b);
    34.     }

    35.     public static void main(String[] args) {
    36.         Scanner scanner = new Scanner(System.in);
    37.         System.out.print("Enter first number: ");
    38.         int num1 = scanner.nextInt();
    39.         System.out.print("Enter second number: ");
    40.         int num2 = scanner.nextInt();

    41.         System.out.println("\nSwapping using a temporary variable:");
    42.         swapWithTemp(num1, num2);

    43.         System.out.println("\nSwapping without using a temporary variable:");
    44.         swapWithoutTemp(num1, num2);

    45.         System.out.println("\nSwapping using XOR operator:");
    46.         swapWithXOR(num1, num2);
    47.         
    48.         System.out.println("\nSwapping using a single statement:");
    49.         swapSingleStatement(num1, num2);

    50.         scanner.close();
    51.     }
    52. }


    Servlet Tutorial

    Introduction to Servlets:

    • Java servlets are small, platform-independent Java programs that can be used to extend the functionality of a Web server in variety of ways.
    • Small java programs compiled to bytecode that can be loaded dynamically and that extends the capabilities of the host.
    •  A client program , which could be a web browser or some other program that can make connections across the internet, accesses a web server and makes a request.
    • This request is processed by the servlet engine that runs with the web server , which returns response to a servlet.
    • the servlet in turn sends a response in HTTP form to the client.
    • In functionality servlets lie somewhere between Common Gateway Interface (CGI) programs.

    What is Servlet? 

    •  Servlet is a java based web technology to develop server side programs to make a web site interactive.
    • Servlet is an API.
    • A collection of library interfaces and classes of two pavkages is nothing but servlet API.
    • javax.servlet.
    • javax.servlet.http
    • A collection of library methods of above two packages is nothing but servlet API.
    • Servlet is specification.
    • Servlet is a J2EE technology.

    A Servlet is a Java programming language class that extends the capabilities of a server to handle client requests and generate dynamic web content. Servlets form the foundation of Java-based web development and are essential for common operations like login systems, form processing, and session management.

    In this tutorial, you'll learn how to set up, create, and deploy Servlets while understanding key concepts like HTTP methods, session management, and more.

    Prerequisites

    Before you dive in, make sure you have:

    1. Basic knowledge of Java programming.
    2. JDK (Java Development Kit) installed.
    3. A web server like Apache Tomcat.
    4. An IDE (Eclipse, IntelliJ, or NetBeans).
    5. Familiarity with HTML and web concepts (optional but helpful).

    Setting Up Your Servlet Project

    Step 1: Create a Dynamic Web Project

    1. In your IDE (e.g., Eclipse), create a Dynamic Web Project.
    2. Name it ServletDemo and configure Tomcat as the runtime server.

    Step 2: Add Servlet Dependencies

    For Maven projects, add the javax.servlet dependency into your pom.xml file:

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    

    Creating Your First Servlet

    Let's build a simple "Hello World" Servlet.

    Step 1: Create a Servlet Class

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class HelloServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h1>Hello, World! This is my first Servlet.</h1>");
            out.println("</body></html>");
        }
    }
    

    Step 2: Configure Servlet Mapping

    In web.xml (or, for modern setups, use annotations):

    <servlet>
      <servlet-name>HelloServlet</servlet-name>
      <servlet-class>HelloServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    

    Alternatively, use annotations in the Servlet class:

    @WebServlet("/hello")
    public class HelloServlet extends HttpServlet { ... }
    

    Step 3: Deploy and Test

    1. Deploy the project to Tomcat.
    2. Visit http://localhost:8080/ServletDemo/hello to see the output!

    Handling Different HTTP Methods

    Servlets can handle different HTTP request types using methods such as doGet() and doPost().

    Example: Handling a POST Request

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String username = request.getParameter("username");
        response.getWriter().println("Welcome, " + username + "!");
    }
    

    An HTML Form to Test the POST Request:

    <form action="hello" method="post">
      <input type="text" name="username">
      <input type="submit" value="Submit">
    </form>
    

    Important Servlet Concepts

    1. Request and Response Objects:

      • HttpServletRequest: Contains client request data (parameters, headers).
      • HttpServletResponse: Sends data back to the client.
    2. Session Management:
      Use HttpSession to track user sessions:

      HttpSession session = request.getSession();
      session.setAttribute("user", "John");
      
    3. Request Dispatching:
      Forward requests to other resources:

      RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
      dispatcher.forward(request, response);
      
    4. Filters:
      Intercept requests/responses for logging, authentication, etc.

    Servlet Development Best Practices

    1. Separation of Concerns: Keep business logic separate from presentation (use JSP or MVC frameworks).
    2. Use Annotations: Simplify configuration with @WebServlet, @WebFilter, etc.
    3. Exception Handling: Implement error pages for uncaught exceptions.
    4. Security: Sanitize inputs, use HTTPS, and manage sessions securely.


    Servlets are a powerful tool in Java web development. Learning them provides a strong foundation for working with advanced frameworks like Spring MVC or Jakarta EE. Start by experimenting with small projects, session management, and later integrate databases to build full-stack applications.

    read more

    Next Steps

    • Explore JSP (JavaServer Pages) for dynamic views.
    • Learn about Servlet Context and Listeners.
    • Dive into Spring Boot for modern web development..
    Select Menu