Skip to main content

Posts

Showing posts with the label Unit 2 - Classes Objects and Methods

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

The final keyword

The `final` keyword in Java is used to define constants, prevent method overriding, and create immutable classes. Here are the main uses of the `final` keyword: 1. Final Variables: When applied to a variable, the `final` keyword indicates that the variable's value cannot be changed once initialized. 2. Final Methods: When applied to a method, the `final` keyword indicates that the method cannot be overridden by subclasses. This is commonly used in class inheritance to enforce certain behaviors that should not be modified. 3. Final Classes: When applied to a class, the `final` keyword indicates that the class cannot be subclassed. This is often used to create immutable classes, which cannot be extended or modified. Here are some examples to illustrate the usage of the `final` keyword: Final Variables: public class FinalExample {     final int MAX_VALUE = 100; // Constant variable     public static void main(String[] args) {         FinalExample obj = new FinalExample();         //

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.

Java Modifiers

Java Modifiers In Java, modifiers are keywords that provide additional information about classes, methods, and variables. They modify the default behavior of these elements. There are two main categories of modifiers: **access modifiers** and **non-access modifiers.** Access Modifiers: 1. Private: - Description:  The private modifier restricts access to members (fields and methods) within the same class.    public class MyClass {     private int privateField;     private void privateMethod() {         System.out.println("Private method");     } } 2. Default (Package-Private): - Description:  Default access means that members are accessible within the same package. class DefaultAccessClass {     int defaultField;     void defaultMethod() {         System.out.println("Default method");     } } 3. Protected: - Description:  Protected access allows members to be accessed within the same package and by subclasses. package mypackage; public class ProtectedClass {     prot

Java Access Control

Java Access Control Overview: In Java, access control determines the visibility and accessibility of classes, methods, and fields within the same class, package, or different packages. There are four access control modifiers in Java: private: Access is limited to the class itself. Fields, methods, and inner classes can be private. default: Access is limited to the package (no modifier is needed). Fields, methods, and classes without any specified modifier have default access. protected: Access is limited to the package and subclasses. Fields, methods, and classes can be protected. public: Access is not restricted. Fields, methods, and classes can be accessed from any class. Examples: Private Access Modifier: public class MyClass {     private int privateField;     private void privateMethod() {         System.out.println("Private method");     } } Default Access Modifier: class DefaultAccessClass {     // Default access fields and methods     int defaultField;     void defaul

Java finalize() Method

Java finalize() Method Overview: - Purpose:  The `finalize()` method in Java is used for performing cleanup operations or releasing resources before an object is garbage-collected. - Invocation:  The `finalize()` method is automatically invoked by the garbage collector just before an object is reclaimed. - Class Involvement:  The `finalize()` method is defined in the `Object` class, and any class can override it to customize cleanup actions. Example: public class ResourceHolder {     // Some resource or setup in the constructor     public ResourceHolder() {         System.out.println("ResourceHolder object created");     }     // Cleanup or resource release in the finalize method     @Override     protected void finalize() throws Throwable {         try {             // Cleanup operations             System.out.println("ResourceHolder object being finalized");         } finally {             // Call the finalize method of the superclass             super.finalize();

static keyword

In Java, the `static` keyword is used to declare members (variables and methods) that belong to the class rather than to instances of the class. When a member is declared as static, it means that there is exactly one copy of that member shared by all instances of the class. The `static` keyword can be applied to variables, methods, and nested classes. Here's a breakdown of how `static` is used: 1. Static Variables (Class Variables):    public class MyClass {        // Static variable        static int count;        public MyClass() {            // Incrementing the static variable in the constructor            count++;        }    }    In the example above, `count` is a static variable, and its value is shared among all instances of the `MyClass`. 2. Static Methods:    public class MathUtils {        // Static method        public static int add(int a, int b) {            return a + b;        }    }    The `add` method in the `MathUtils` class is declared as static. It can be called

this keyword

 In Java, the "this" keyword is a reference variable that refers to the current object. It is used within the instance methods of a class to refer to the current instance of the class. The primary purposes of the "this" keyword are: 1. Distinguishing Instance Variables:  When an instance method has parameters or local variables with the same names as instance variables, using "this" helps to differentiate between the instance variables and local variables. For example:     public class MyClass {         // Instance variable         private int myValue;         // Constructor with a parameter         public MyClass(int myValue) {             // Using "this" to distinguish instance variable             this.myValue = myValue;         }         // Method using "this" to access instance variable         public void printValue() {             System.out.println("Instance variable value: " + this.myValue);         }     }     In the

New Operator in Java

 New Operator in Java In Java, the `new` operator is used to create an instance of a class or to allocate memory for an array. It is a fundamental operator and plays a crucial role in the object-creation process. Let's explore how the `new` operator works in different contexts. Creating Objects The primary use of the `new` operator is to create objects by invoking a class constructor. The general syntax is as follows: ClassName objectReference = new ClassName(); Here, `ClassName` is the name of the class, and `objectReference` is a reference variable that will refer to the newly created object. Example: // Define a simple class class MyClass {     int value;     MyClass(int value) {         this.value = value;     } } public class ObjectCreationExample {     public static void main(String[] args) {         // Create an instance of MyClass using the new operator         MyClass myObject = new MyClass(42);         // Access and print the value         System.out.println("Object

Passing and Returning Objects in Java Methods

Passing and Returning Objects in Java Methods In Java, objects can be passed as parameters to methods and returned from methods just like other primitive data types. This allows for flexibility and the manipulation of object state within methods. Let's explore how passing and returning objects work in Java. Passing Objects as Parameters When you pass an object as a parameter to a method, you are essentially passing a reference to that object. This means that changes made to the object inside the method will affect the original object outside the method.  Example: class Car {     String model;     Car(String model) {         this.model = model;     } } public class CarProcessor {     // Method to modify the Car object     static void modifyCar(Car car, String newModel) {         car.model = newModel;     }     public static void main(String[] args) {         Car myCar = new Car("Toyota");         System.out.println("Before: " + myCar.model);         // Passing th

Recursion in Java

 Recursion in Java Recursion  is a programming concept where a method calls itself to solve a problem. It involves breaking down a problem into smaller subproblems, solving each subproblem, and combining the results to obtain the final solution. Recursive solutions are particularly useful for problems that exhibit repetitive and self-similar structures. Example: Let's take an example of a factorial function to understand recursion. public class FactorialCalculator {     // Recursive method to calculate factorial     public static int factorial(int n) {         // Base case: factorial of 0 is 1         if (n == 0) {             return 1;         } else {             // Recursive case: n! = n * (n-1)!             return n * factorial(n - 1);         }     }     public static void main(String[] args) {         int number = 5;         int result = factorial(number);         System.out.println("Factorial of " + number + " is: " + result);     } } In this example, the

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

Constructor Overloading in Java

Constructor Overloading in Java Constructor overloading  is a concept in Java where a class can have multiple constructors with different parameter lists. Each constructor provides a different way to initialize an object. The choice of constructor to be invoked is determined by the number and types of arguments passed during object creation. Example: public class Car {     // Attributes     String make;     String model;     int year;     // Default Constructor     public Car() {         make = "Unknown";         model = "Unknown";         year = 0;     }     // Parameterized Constructor 1     public Car(String make, String model) {         this.make = make;         this.model = model;         this.year = 0;     }     // Parameterized Constructor 2     public Car(String make, String model, int year) {         this.make = make;         this.model = model;         this.year = year;     }     // Method to Display Car Information     void displayInfo() {         System.

Class, Object, Object Reference, Method and Constructor in Java

Class, Object, Object Reference, Method, and Constructor in Java Class: In Java, a class  is a blueprint or template that defines the structure and behavior of objects. It acts as a template for creating objects, encapsulating data (attributes) and methods (functions) that operate on that data. Syntax: public class ClassName {     // Attributes     dataType attributeName;     // Constructor     public ClassName(parameters) {         // Initialization code     }     // Methods     returnType methodName(parameters) {         // Method body     } } Object: An object  is an instance of a class. It is a concrete realization of the class blueprint, possessing its own unique state (attributes) and behavior (methods). Objects represent real-world entities and are created based on the class template. Object Creation: ClassName objectName = new ClassName(arguments); Method: A method is a function defined within a class that performs a specific task or action. It represents the behavior associat