Skip to main content

Socket (TCP & UDP) communication in Java

Socket communication in Java enables communication between two endpoints over a network. There are two main types of sockets: TCP sockets and UDP sockets. Let's explain both types with examples: TCP Socket Communication: 1. **Server Side**:    - The server creates a `ServerSocket` object to listen for incoming connections on a specific port.    - When a client connects, the server accepts the connection and creates a `Socket` object to communicate with the client.    - The server reads from and writes to the socket's input and output streams to communicate with the client. import java.io.*; import java.net.*; public class TCPServer {     public static void main(String[] args) throws IOException {         ServerSocket serverSocket = new ServerSocket(12345);         System.out.println("Server started. Waiting for client...");         Socket clientSocket = serverSocket.accept();         System.out.println("Client connected.");         BufferedReader in = new Bu

Sorting using `Comparable` and `Comparator`

Sorting using `Comparable` and `Comparator` in Java provides flexibility in sorting objects based on natural ordering (defined by the object itself) or custom ordering (defined externally). Let's explain and demonstrate both:

Sorting Using Comparable:

1. Explanation:

   - Objects implementing `Comparable` interface provide a natural ordering based on their intrinsic properties.

   - The `compareTo()` method is overridden to define how objects should be compared to each other.


2. Demonstration:

   - Let's consider a class `Employee` with properties `id` and `name`. We'll implement `Comparable` to sort employees based on their ids.


   public class Employee implements Comparable<Employee> {

       private int id;

       private String name;


       // Constructor, getters, setters


       @Override

       public int compareTo(Employee other) {

           return Integer.compare(this.id, other.id);

       }

   }



   - Now, we can use `Arrays.sort()` to sort an array of `Employee` objects based on their ids.



   Employee[] employees = {emp1, emp2, emp3};

   Arrays.sort(employees);



Sorting Using Comparator:


1. Explanation:

   - `Comparator` interface provides a way to define custom sorting logic externally, independent of the object being sorted.

   - Custom `Comparator` implementations can be provided for different sorting criteria.


2. Demonstration:

   - Let's continue with the `Employee` class. Now, we want to sort employees based on their names. We'll implement a custom `Comparator` for this.



   public class NameComparator implements Comparator<Employee> {

       @Override

       public int compare(Employee emp1, Employee emp2) {

           return emp1.getName().compareTo(emp2.getName());

       }

   }



   - We can then use this comparator with `Arrays.sort()` to sort employees by name.



   Employee[] employees = {emp1, emp2, emp3};

   Arrays.sort(employees, new NameComparator());



Comparison:


- Comparable:

  - Used when objects have a natural ordering.

  - Changes to the class itself.

  - One default ordering.


- Comparator:

  - Used for custom ordering or when objects don't implement `Comparable`.

  - No changes to the class being sorted.

  - Multiple custom orderings possible.


Complete Example:


import java.util.Arrays;

import java.util.Comparator;


class Employee implements Comparable<Employee> {

    private int id;

    private String name;


    public Employee(int id, String name) {

        this.id = id;

        this.name = name;

    }


    // Getters, setters, etc.


    @Override

    public int compareTo(Employee other) {

        return Integer.compare(this.id, other.id);

    }


    @Override

    public String toString() {

        return "Employee{" +

                "id=" + id +

                ", name='" + name + '\'' +

                '}';

    }

}


class NameComparator implements Comparator<Employee> {

    @Override

    public int compare(Employee emp1, Employee emp2) {

        return emp1.getName().compareTo(emp2.getName());

    }

}


public class SortingDemo {

    public static void main(String[] args) {

        Employee[] employees = {

                new Employee(3, "John"),

                new Employee(1, "Alice"),

                new Employee(2, "Bob")

        };


        // Sorting using Comparable (by id)

        Arrays.sort(employees);

        System.out.println("Sorted by id:");

        for (Employee emp : employees) {

            System.out.println(emp);

        }


        // Sorting using Comparator (by name)

        Arrays.sort(employees, new NameComparator());

        System.out.println("\nSorted by name:");

        for (Employee emp : employees) {

            System.out.println(emp);

        }

    }

}



This example demonstrates sorting `Employee` objects both by their ids (using `Comparable`) and by their names (using `Comparator`).

Comments

Popular posts from this blog

Method Overloading in Java

Method Overloading in Java Method Overloading  is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists. The methods can have a different number or types of parameters. The decision on which method to invoke is made by the compiler based on the arguments provided during the method call.  Example: public class Calculator {     // Method to add two integers     public int add(int a, int b) {         return a + b;     }     // Method to add three integers     public int add(int a, int b, int c) {         return a + b + c;     }     // Method to add two doubles     public double add(double a, double b) {         return a + b;     }     // Method to concatenate two strings     public String concatenate(String str1, String str2) {         return str1 + str2;     } } Method Overloading in Action: public class Main {     public static void main(String[] args) {         Calculator calculator = new Calculator();         // Overloaded meth

Java Runtime Environment (JRE)

Definition : Java Runtime Environment (JRE) is a set of software tools and libraries that enables the execution of Java applications. It provides the necessary runtime support for Java programs to run on various devices and platforms. Components of Java Runtime Environment (JRE): Java Virtual Machine (JVM): Definition: The JVM is a crucial component of the JRE responsible for executing Java bytecode. Functionality: It interprets Java bytecode or, in some cases, uses Just-In-Time (JIT) compilation to translate bytecode into native machine code for improved performance. Importance: JVM abstracts the underlying hardware, allowing Java programs to be platform-independent. Class Libraries: Definition: JRE includes a set of precompiled classes and methods that Java applications can utilize. Functionality: These classes cover a wide range of functionalities, from basic data structures to networking. Importance: Class libraries provide a foundation for developers, offering reusable code