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(); ...
The instanceof operator in Java is used to test whether an object is an instance of a particular class, interface, or a subclass/interface of a given type. It returns a boolean value indicating whether the object on the left-hand side is an instance of the specified type. Syntax: object instanceof type object: The object to be tested. type: The class or interface to check against. Example: class Animal {} class Dog extends Animal {} class Cat extends Animal {} public class InstanceOfExample { public static void main(String[] args) { Animal myDog = new Dog(); Animal myCat = new Cat(); // Using instanceof to check object types System.out.println("Is myDog a Dog? " + (myDog instanceof Dog)); // true System.out.println("Is myDog a Cat? " + (myDog instanceof Cat)); // false System.out.println("Is myCat a Do...