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

Understanding of Java Object Class

The `Object` class in Java serves as the root of the class hierarchy. Here are some key points to understand about the `Object` class along with examples:


1. Default Superclass: If a class doesn't extend any other class explicitly, it implicitly inherits from the `Object` class.

   public class MyClass {

       // MyClass inherits from Object implicitly

   }


2. toString() Method: Provides a string representation of the object. It is commonly overridden to return meaningful information about the object.


   public class Student {

       private String name;

       private int age;


       // Constructor and other methods...


       @Override

       public String toString() {

           return "Student{name='" + name + "', age=" + age + '}';

       }

   }


3. equals() Method: Compares two objects for equality. It is overridden to compare the contents of objects rather than their references.


   public class Point {

       private int x, y;


       // Constructor and other methods...


       @Override

       public boolean equals(Object obj) {

           if (this == obj) return true;

           if (obj == null || getClass() != obj.getClass()) return false;

           Point other = (Point) obj;

           return x == other.x && y == other.y;

       }

   }


4. hashCode() Method: Returns a hash code value for the object, used in hash-based collections. It is overridden for consistency with the `equals()` method.


   @Override

   public int hashCode() {

       return Objects.hash(x, y);

   }


5. getClass() Method: Returns the runtime class of an object. It is useful for obtaining metadata about objects at runtime.

   Object obj = new Student();

   Class<?> clazz = obj.getClass();

   System.out.println("Runtime class of obj: " + clazz.getName());


6. clone() Method: Creates and returns a shallow copy of the object. It can be overridden to support copying of custom objects.


   @Override

   protected Object clone() throws CloneNotSupportedException {

       return super.clone();

   }


7. finalize() Method: Called by the garbage collector before reclaiming the memory occupied by the object. It's rarely used due to unpredictable behavior and is deprecated in newer versions of Java.


   @Override

   protected void finalize() throws Throwable {

       // Cleanup code before garbage collection

       super.finalize();

   }


8. wait(), notify(), notifyAll() Methods: Used for inter-thread communication and synchronization. They are invoked on objects within synchronized blocks.


   synchronized (obj) {

       obj.wait();     // Causes the current thread to wait until another thread invokes notify() or notifyAll() on the same object.

       obj.notify();   // Wakes up a single thread that is waiting on this object's monitor.

       obj.notifyAll();// Wakes up all threads that are waiting on this object's monitor.

   }


By understanding and utilizing the `Object` class and its methods effectively, developers can enhance their Java programs with common functionalities and behaviors.


____________________


In Java, the `Object` class is the root class of all classes. Every class in Java is directly or indirectly derived from the `Object` class. It resides in the `java.lang` package and provides several methods that are common to all objects. Here are some key points about the `Object` class:


1. Default Superclass: If a class does not explicitly extend any other class, it implicitly extends the `Object` class.

2. toString() Method: The `toString()` method returns a string representation of the object. By default, it returns the class name followed by the memory address of the object in hexadecimal format. It is often overridden in subclasses to provide more meaningful information about the object.

3. equals() Method: The `equals()` method is used to compare two objects for equality. By default, it compares object references (memory addresses) for equality. It is commonly overridden in subclasses to provide custom equality comparison based on the object's state.

4. hashCode() Method: The `hashCode()` method returns a hash code value for the object. By default, it returns a unique integer value based on the memory address of the object. It is often overridden in subclasses to generate hash codes based on the object's state.

5. getClass() Method: The `getClass()` method returns the runtime class of an object as a `Class` object. It allows you to obtain metadata about the object's class at runtime.

6. clone() Method: The `clone()` method creates and returns a shallow copy of the object. It performs a field-by-field copy of the object's state, but does not create copies of objects referenced by the original object's fields.

7. finalize() Method: The `finalize()` method is called by the garbage collector before reclaiming the memory occupied by the object. It can be overridden in subclasses to perform cleanup operations before the object is garbage collected, but its usage is discouraged in modern Java programming due to unpredictability.

8. wait(), notify(), notifyAll() Methods: These methods are used for inter-thread communication and synchronization. They are used in conjunction with the `synchronized` keyword to coordinate the execution of multiple threads.


By understanding the `Object` class and its methods, Java developers can leverage its functionality to implement common behavior and functionality across different classes in their applications.

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