Skip to main content

Posts

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

Garbage collection (GC)

Garbage collection (GC) is a fundamental feature of the Java Virtual Machine (JVM) that manages memory allocation and deallocation in Java programs. It automatically identifies and reclaims memory that is no longer in use, freeing it up for future allocation. Here's an overview of garbage collection in Java: 1. Automatic Memory Management:    - Unlike languages like C and C++, where developers manually allocate and deallocate memory using `malloc()` and `free()`, Java employs automatic memory management through garbage collection.    - With automatic memory management, developers don't need to explicitly deallocate memory, reducing the risk of memory leaks and segmentation faults. 2. Heap Memory:    - In Java, objects are allocated memory from the heap, which is a region of memory managed by the JVM.    - The heap is divided into two main areas: the young generation and the old generation (also known as the new generation and the tenured generation, respectively).    - The youn

Object Life Time

 In Java, the lifetime of an object refers to the duration during which the object exists in memory before it is eligible for garbage collection. The Java Virtual Machine (JVM) automatically manages memory allocation and deallocation for objects through a process called garbage collection. Here's a brief overview of the different stages in the lifetime of an object in Java: 1. Creation: The object is created using the `new` keyword or through other means such as object cloning or deserialization. Memory is allocated for the object on the heap. 2. Initialization: The object's fields are initialized either with default values (for instance variables) or with user-defined values (through constructors or initialization blocks). 3. Usage: The object is used by the program, and its methods and fields are accessed or modified as needed. 4. Scope: The object remains in scope as long as there are references to it. If the object is assigned to a variable or passed as an argument to a m

Wrapper classes

Wrapper classes in Java are used to convert primitive data types into objects (i.e., wrapping primitive values) so that they can be included in Java collections, passed as method arguments where objects are required, and used in other situations where objects are needed instead of primitives. Each primitive data type in Java has a corresponding wrapper class. Here are the wrapper classes for primitive data types: 1. Byte: `java.lang.Byte` 2. Short: `java.lang.Short` 3. Integer: `java.lang.Integer` 4. Long: `java.lang.Long` 5. Float: `java.lang.Float` 6. Double: `java.lang.Double` 7. Character: `java.lang.Character` 8. Boolean: `java.lang.Boolean` Wrapper classes provide methods to perform various operations on the wrapped primitive value, such as converting it to other data types, comparing values, and parsing strings to primitive values. They also provide constants for representing the maximum and minimum values of the corresponding primitive data type. Here's an example demo

Abstract Class

An abstract class in Java is a class that cannot be instantiated directly and is designed to be subclassed. It serves as a blueprint for other classes and may contain one or more abstract methods, which are methods declared without a body. Here are some key points about abstract classes: 1. Cannot be instantiated:  An abstract class cannot be instantiated on its own. Instead, it must be subclassed by other classes, which provide concrete implementations for its abstract methods. 2. May contain abstract methods:  An abstract class may contain abstract methods, which are declared using the abstract keyword and do not have a body. Subclasses of the abstract class must provide concrete implementations for these abstract methods. 3. Can contain concrete methods:  In addition to abstract methods, an abstract class can also contain concrete methods with implementations. These methods are inherited by subclasses but can be overridden if needed. 4. Can contain fields:  Abstract classes can have

Anonymous inner class

Anonymous inner class An anonymous inner class in Java is a class without a name that's defined and instantiated in a single expression. It's often used to create instances of classes that implement interfaces or extend classes without explicitly defining a new class. Here's an example: public class Main {     interface Greeting {         void greet();     }     public static void main(String[] args) {         // Creating an anonymous inner class that implements the Greeting interface         Greeting greeting = new Greeting() {             @Override             public void greet() {                 System.out.println("Hello from anonymous inner class!");             }         };         // Invoking the method defined in the anonymous inner class         greeting.greet();     } } Explanation: - In the example above, an anonymous inner class is created that implements the `Greeting` interface. - The `greet()` method is overridden within the anonymous inner class to

Inner Class

 Inner Class: - An inner class is a class that is defined within another class and belongs to the instance of the outer class. - Unlike nested static classes, inner classes have access to the instance variables and methods of the outer class. - Inner classes can be non-static or static. Example: class Outer {     private int outerVar;     class Inner {         void display() {             System.out.println("Inner class method, outerVar = " + outerVar);         }     } } Explanation: In the example above, the Inner class is an inner class of the Outer class. It has access to the private member `outerVar` of the Outer class. Sample Use: Inner classes are useful when you want to encapsulate related functionality within a class and you don't want the inner class to be visible outside of its outer class. They are commonly used in event handling, GUI programming, and implementing data structures. Analogy: Imagine a car (Outer class) with various components like engine, wheels,

Nested Class

 Nested Class: - A nested class is a class that is defined within another class. - It can be static or non-static and can access the members of the enclosing class. - Nested classes are mainly used to logically group classes that are only used in one place or for better encapsulation and organization of code. Example: class Outer {     private int outerVar;     class Inner {         void display() {             System.out.println("Inner class method, outerVar = " + outerVar);         }     } } Explanation: In the example above, the Inner class is nested within the Outer class. It has access to the private member `outerVar` of the Outer class. Sample Use: Nested classes are commonly used in scenarios where a class is only relevant within the context of another class. For example, in GUI programming, a Button class might be nested within a Window class because it only makes sense to have buttons within a window. Analogy: Imagine a company (Outer class) with various departments.