Home page

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, May 29, 2024

Find first and last occurrence of the letter ‘s’ in samosa with index number

public class Main { 
 public static void main(String[] args) { 
     String str = "samosa"; 
     int firstIndex = str.indexOf('s'); 
     int lastIndex = str.lastIndexOf('s'); 

    System.out.println("First occurrence of 's' in " + str + " is at index " + firstIndex); 
    System.out.println("Last occurrence of 's' in " + str + " is at index " + lastIndex); 
     
}

Tuesday, August 8, 2023

Access Modifiers in JAVA

Access Modifiers in Java

Access Modifier Visibility Within Same Class Within Package Subclass (Inheritance) Outside Package
Default (no modifier) Package-private
public Public
protected Package-private + Subclass
private Class-private

Monday, August 7, 2023

Difference between method overloading and overriding in JAVA

Method Overloading vs. Method Overriding

Aspect Method Overloading Method Overriding
Purpose Provide multiple versions of a method in the same class based on different parameter lists. Provide a specific implementation of a method in a subclass that is already defined in its superclass.
Inheritance Occurs within the same class. Occurs between a superclass and its subclass.
Method Signature Method names must be the same, but parameter lists must be different (type, number, or order). Method names, return types, and parameter lists must be the same.
Compile-time Resolution Determined at compile time based on method signature and parameter types. Determined at runtime based on the actual object's type (dynamic polymorphism).
Return Type Overloading can have the same or different return types. Overriding must have the same return type (or covariant return type in the case of inheritance).
Access Modifiers Can have different access modifiers. Can have the same or less restrictive access modifiers (cannot be more restrictive).
Exceptions Can have different checked and unchecked exceptions. Cannot throw broader checked exceptions (but can throw narrower or unchecked exceptions).
Static vs. Instance Can involve both static and instance methods. Involves only instance methods (static methods are hidden, not overridden).
Polymorphism Not related to polymorphism. Fundamental for achieving polymorphism and runtime behavior.

Sunday, August 6, 2023

Reverse number in JAVA

Printing a number in reverse order in Java involves extracting the digits of the number one by one and printing them in reverse. Here's the Java code to print a number in reverse order:

public class ReverseNumber {

    public static void main(String[] args) {

        int number = 12345;

        System.out.println("Original number: " + number);

        System.out.print("Number in reverse: ");

        printReverseNumber(number);

    }

    public static void printReverseNumber(int num) {

        while (num > 0) {

            int digit = num % 10; // Extract the last digit

            System.out.print(digit);

            num /= 10; // Remove the last digit

        }

    }

}

Output:
Original number: 12345
Number in reverse: 54321

Explanation:
  1. In this example, we take an integer number (e.g., 12345) as input.
  2. The printReverseNumber method is used to print the digits of the number in reverse order.
  3. Inside the printReverseNumber method, we use a while loop that runs as long as num is greater than 0.
  4. In each iteration of the loop, we extract the last digit of num using the modulus operator (num % 10) and print it.
  5. We then remove the last digit from num by dividing it by 10 (num /= 10).
  6. The loop continues until all digits of the number are printed.
The code prints the original number and then uses the printReverseNumber method to print the number in reverse order by extracting and printing the digits from right to left.

This approach works for positive integers. If you need to handle negative numbers or non-integer values, you can adapt the code accordingly.

Saturday, August 5, 2023

Finally in JAVA

The finally block in Java is used in conjunction with try and catch blocks to ensure that a section of code is executed regardless of whether an exception is thrown or not. The finally block is typically used for cleanup operations, such as releasing resources, closing files, or closing network connections. Here's an overview of when and how to use the finally block in Java:

Purpose:

Cleanup Operations: The primary purpose of the finally block is to perform cleanup tasks that need to be executed regardless of whether an exception occurred or not. This ensures that resources are properly released and the program leaves a consistent state.

Resource Management: It's often used for managing resources like closing files, database connections, network sockets, or any other resources that should be explicitly released when they are no longer needed.

Error Handling: The finally block provides a way to handle exceptions and recover from exceptional situations gracefully while still performing necessary cleanup operations.

How to use the finally block:

try block: Wrap the code that may potentially throw an exception inside a try block.

catch block (optional): Add one or more catch blocks to catch and handle specific exceptions that may be thrown inside the try block.

finally block: Add a finally block after the try and optionally catch blocks. This block contains the cleanup code that you want to ensure gets executed regardless of exceptions.

Example:

import java.io.FileWriter;

import java.io.IOException;

public class FinallyExample {

    public static void main(String[] args) {

        FileWriter writer = null;

        try {

            writer = new FileWriter("output.txt");

            writer.write("Hello, world!");

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (writer != null) {

                try {

                    writer.close(); // Close the file in the finally block

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}

In the above example, the try block attempts to create a FileWriter and write some content to a file. If an IOException occurs, it is caught and printed in the catch block. Regardless of whether an exception occurs or not, the finally block ensures that the FileWriter is properly closed to release system resources.

Remember the following points when using the finally block:
  • The finally block is executed whether an exception is thrown or not in the corresponding try block.
  • If a catch block is present, the finally block executes after the catch block.
  • The finally block is optional. You can have a try block without a catch block, only a catch block, or both.
  • The finally block is typically used for cleanup operations, but it can also contain other statements.
  • Use the finally block to ensure that important cleanup operations are performed, even in the presence of exceptions, and to manage resources properly.

Monday, July 24, 2023

Check given number is palindrome or not in JAVA

A palindrome is a sequence of characters (such as a word, phrase, number, or any other sequence) that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. For example, "radar," "level," and "12321" are all palindromes.

To check whether a given string is a palindrome, you need to compare its characters from both ends inward and ensure that they match.

Here's the Java code to check if a given string is a palindrome:

public class PalindromeCheck {

    public static void main(String[] args) {

        String input = "radar"; // Change this string to test different cases

        boolean isPalindrome = checkPalindrome(input);

        if (isPalindrome) {

            System.out.println("'" + input + "' is a palindrome.");

        } else {

            System.out.println("'" + input + "' is not a palindrome.");

        }

    }

    public static boolean checkPalindrome(String str) {

        str = str.toLowerCase(); // Convert to lowercase for case-insensitive comparison

        int left = 0;

        int right = str.length() - 1;

        while (left < right) {

            char leftChar = str.charAt(left);

            char rightChar = str.charAt(right);

            if (leftChar != rightChar) {

                return false;

            }

            left++;

            right--;

        }

        return true;

    }

}

In this code, the checkPalindrome method takes a string str as input and returns a boolean value indicating whether it is a palindrome or not. We use two pointers, left and right, initialized to the start and end of the string, respectively.

The while loop runs until left is less than right. In each iteration, we compare the characters at positions left and right. If they don't match, the string is not a palindrome, and we return false. Otherwise, we increment left and decrement right to continue comparing the characters inward.

We also convert the input string to lowercase using toLowerCase() to ensure case-insensitive comparison.

The main method calls the checkPalindrome method with a sample string ("radar" in this case) and prints whether the string is a palindrome or not. You can change the input variable to test different cases.

Sunday, July 23, 2023

Swapping two numbers without using 3rd variable in JAVA

  • Using Arithmetic Operations

You can swap two numbers a and b without using a third variable by using basic arithmetic operations like addition and subtraction. This method is applicable to numeric data types (e.g., int, double).

public class SwapWithoutThirdVariable {

    public static void main(String[] args) {

        int a = 10;

        int b = 20;

        System.out.println("Before swapping:");

        System.out.println("a = " + a);

        System.out.println("b = " + b);

        // Swapping using arithmetic operations

        a = a + b;

        b = a - b;

        a = a - b;

        System.out.println("After swapping:");

        System.out.println("a = " + a);

        System.out.println("b = " + b);

    }

}

Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10

  • Using Bitwise XOR Operation:
You can also swap two numbers a and b using the bitwise XOR (^) operation. This method is applicable to integer data types.

public class SwapWithoutThirdVariable {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        System.out.println("Before swapping:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);

        // Swapping using bitwise XOR operation
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

        System.out.println("After swapping:");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10

In both methods, the two numbers are swapped without using an additional third variable. These techniques rely on the mathematical properties of arithmetic or bitwise XOR operations to perform the swap. These methods are efficient and commonly used when you want to swap two variables without using extra memory.

Wednesday, July 12, 2023

Constructor in JAVA

Constructors in Java are special methods used to initialize objects of a class. They have the same name as the class and are called automatically when an object is created. Here's an overview of when and how to use constructors in Java:

Purpose:

  1. Object Initialization: The primary purpose of constructors is to initialize the state (member variables) of an object. They ensure that the object is in a valid and usable state when it is created.
  2. Encapsulation: Constructors provide a way to encapsulate the initialization logic within the class, ensuring that the object is correctly initialized before any operations are performed on it.
  3. Flexibility: Constructors allow you to define different ways to create objects by accepting different sets of parameters, providing flexibility and customization during object creation.

How to use constructors:

  1. Define a constructor: Declare a method with the same name as the class. Constructors do not have a return type, not even void.
  2. Define parameterized constructors (optional): Constructors can accept parameters to initialize member variables based on the provided values.
  3. Use the new keyword to create objects: Instantiate objects using the new keyword followed by the constructor invocation.

Example:

public class Person {

    private String name;

    private int age;

    // Default constructor

    public Person() {

        // Initialization logic

        name = "John Doe";

        age = 0;

    }

    // Parameterized constructor

    public Person(String name, int age) {

        // Initialization logic based on provided parameters

        this.name = name;

        this.age = age;

    }

    // Other methods...

    public static void main(String[] args) {

        // Create objects using constructors

        Person person1 = new Person(); // Invokes the default constructor

        Person person2 = new Person("Alice", 25); // Invokes the parameterized constructor

        // Use the created objects

        System.out.println(person1.getName()); // Output: John Doe

        System.out.println(person2.getName()); // Output: Alice

    }

}

In the above example, the Person class has two constructors. The default constructor initializes the member variables with default values, while the parameterized constructor accepts values for name and age to initialize the object with provided values. In the main method, we create two Person objects using the constructors and access their properties.

Remember the following points when using constructors:

  1. Constructors have the same name as the class and are called automatically when an object is created.
  2. Constructors do not have a return type, not even void.
  3. Constructors can be overloaded, allowing you to define different ways to create objects based on varying parameter lists.
  4. If you don't provide a constructor explicitly, a default constructor (with no parameters) is automatically created by the compiler.
  5. Use constructors to initialize the state of objects and ensure they are in a valid and usable state. Constructors provide flexibility, encapsulation, and customization during object creation.

Tuesday, July 11, 2023

HashMap in JAVA

The HashMap class in Java provides an implementation of the Map interface using a hash table data structure. It stores key-value pairs and allows efficient retrieval and insertion operations. Here's an overview of when and how to use HashMap in Java:

Purpose:

  1. Key-Value Mapping: The main purpose of using a HashMap is to store key-value pairs, where each key is unique within the map.
  2. Efficient Retrieval: HashMap provides fast retrieval of values based on their associated keys. It uses hashing to achieve constant-time complexity O(1) for retrieval operations (on average).
  3. Dynamic Size: HashMap is suitable when the size of the map can vary dynamically. It automatically handles resizing and rehashing to maintain performance.

How to use HashMap:

  1. Import the HashMap class: Before using HashMap, import the java.util.HashMap class.
  2. Create a HashMap instance: Instantiate a HashMap object, specifying the types for the key and value.
  3. Add key-value pairs: Use the put method to add key-value pairs to the HashMap.
  4. Retrieve values: Use the get method to retrieve values based on their keys.
  5. Perform other operations: Use various methods available in HashMap, such as containsKey, remove, size, etc., to perform operations on the map.

Example:

import java.util.HashMap;

public class HashMapExample {

    public static void main(String[] args) {

        // Create a HashMap of names and ages

        HashMap<String, Integer> personMap = new HashMap<>();

        // Add key-value pairs to the HashMap

        personMap.put("Alice", 25);

        personMap.put("Bob", 30);

        personMap.put("Charlie", 35);

        // Retrieve values based on keys

        int age = personMap.get("Bob");

        System.out.println(age); // Output: 30

        // Check if a key is present

        boolean containsKey = personMap.containsKey("Alice");

        System.out.println(containsKey); // Output: true

        // Remove a key-value pair

        personMap.remove("Charlie");

        System.out.println(personMap); // Output: {Alice=25, Bob=30}

        // Get the size of the HashMap

        int size = personMap.size();

        System.out.println(size); // Output: 2

    }

}

In the above example, we create a HashMap called personMap to store names as keys and ages as values. We add key-value pairs to the map, retrieve values based on keys, check if a key is present, remove a key-value pair, and retrieve the size of the map.

Remember the following points when using HashMap:

  • HashMap does not maintain any order of key-value pairs. If you need a specific order, consider using LinkedHashMap.
  • Keys in a HashMap must be unique. If a duplicate key is added, the existing value is replaced with the new one.
  • HashMap allows null as both keys and values.
  • The performance of HashMap depends on a good distribution of hash codes for the keys to avoid collisions.
  • Use HashMap when you need to store key-value pairs and require efficient retrieval based on keys. It provides fast access to values and is suitable for dynamic-sized maps.

Monday, July 10, 2023

TreeSet in JAVA

The TreeSet class in Java is an implementation of the Set interface that provides a sorted, ordered set of elements. It internally uses a self-balancing binary search tree (specifically, a Red-Black tree) to maintain the elements in a sorted order. Here's an overview of when and how to use TreeSet in Java:

Purpose:

Sorted Order: The main purpose of using a TreeSet is to maintain elements in a sorted order based on their natural ordering (if they implement the Comparable interface) or a custom comparator provided during TreeSet instantiation.

Efficient Search: TreeSet provides efficient search operations (contains, containsAll, ceiling, floor, etc.) with a time complexity of O(log N) due to the underlying binary search tree structure.

Unique Elements: Like other implementations of Set, TreeSet does not allow duplicate elements. It ensures that each element is unique within the set.

How to use TreeSet:

Import the TreeSet class: Before using TreeSet, import the java.util.TreeSet class.

Create a TreeSet instance: Instantiate a TreeSet object, specifying the element type either by using the diamond operator (<>) or providing the type explicitly.

Add elements: Use the add method to add elements to the TreeSet. The elements will be automatically sorted based on their natural ordering or the provided comparator.

Perform operations: Use various methods available in TreeSet such as contains, remove, size, etc., to perform operations on the set.

Example:

import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {

        // Create a TreeSet of integers

        TreeSet<Integer> numbers = new TreeSet<>();

        // Add elements to the TreeSet

        numbers.add(5);

        numbers.add(2);

        numbers.add(8);

        numbers.add(1);

        numbers.add(4);

        // Print the TreeSet

        System.out.println(numbers); // Output: [1, 2, 4, 5, 8]

        // Check if an element is present

        boolean containsFive = numbers.contains(5);

        System.out.println(containsFive); // Output: true

        // Remove an element

        numbers.remove(2);

        System.out.println(numbers); // Output: [1, 4, 5, 8]

        // Get the size of the TreeSet

        int size = numbers.size();

        System.out.println(size); // Output: 4

    }

}

In the above example, we create a TreeSet called numbers to store integers. We add elements to the set, and the TreeSet automatically sorts them in ascending order. We can perform various operations such as checking for the presence of an element, removing an element, and retrieving the size of the set.

Remember the following points when using TreeSet:

  1. The elements in a TreeSet must either implement the Comparable interface (to define their natural ordering) or a custom Comparator must be provided during TreeSet instantiation.
  2. TreeSet does not allow null elements. However, if a custom Comparator is used, it should be capable of handling null values.
  3. TreeSet provides efficient search operations due to the underlying binary search tree structure.
  4. The elements in a TreeSet are stored in sorted order, which allows for easy iteration in ascending or descending order.
  5. Use TreeSet when you need a set of elements to be maintained in a sorted order. It provides efficient search operations and ensures uniqueness of elements.

Sunday, July 9, 2023

Constructor overloading in JAVA

Constructor overloading in Java allows you to define multiple constructors within a class, each with a different parameter list. Each constructor provides a different way to create objects of the class based on varying parameters. Here's an overview of when and how to use constructor overloading in Java:

Purpose:

Flexibility: Constructor overloading provides flexibility by allowing objects to be created with different sets of initial values or different combinations of parameters.

Ease of Use: Constructor overloading makes it convenient for users of the class to create objects by providing multiple ways to initialize the object's state.

Encapsulation: Constructors with different parameter lists can enforce different levels of initialization or data validation, ensuring that objects are properly initialized.

How to use constructor overloading:

Define multiple constructors within a class with different parameter lists (number, type, or order of parameters).

Each constructor should have a unique combination of parameter signatures to differentiate them during object creation.

Each constructor should perform the necessary initialization based on the provided parameters.

Example:

public class Person {

    private String name;

    private int age;

    public Person() {

        // Default constructor with no parameters

    }

    public Person(String name) {

        this.name = name;

    }

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

}

In the above example, the Person class has multiple constructors with different parameter lists. The first constructor is a default constructor with no parameters. The second constructor accepts only the name parameter, allowing users to create a Person object with just a name. The third constructor accepts both the name and age parameters, providing the option to specify both attributes during object creation.

By using constructor overloading, users of the Person class can choose the appropriate constructor based on their requirements and the available information.

To create objects using the overloaded constructors:
Person person1 = new Person(); // Invokes the default constructor
Person person2 = new Person("John"); // Invokes the constructor with the name parameter
Person person3 = new Person("Jane", 25); // Invokes the constructor with both name and age parameters

Remember the following points when using constructor overloading:

Each constructor should have a unique combination of parameter types or the number and order of parameters to differentiate them.
The compiler determines which constructor to invoke based on the arguments provided during object creation.
Constructor overloading allows for flexibility in object initialization and provides convenience to the users of the class.
Constructor overloading is useful when you want to provide multiple ways to initialize objects, allowing users to create objects with different sets of initial values or different combinations of parameters.

Saturday, July 8, 2023

Method overriding in JAVA

Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Method overriding is used to achieve polymorphism, where a subclass can define its behavior while maintaining a common interface. Here's an overview of when and how to use method overriding in Java:

Purpose:

Modify Behavior: Method overriding allows a subclass to modify or extend the behavior of a method inherited from its superclass.

Polymorphism: Method overriding enables polymorphism, where an object of the subclass can be treated as an object of the superclass, providing flexibility and code reuse.

Follows the "IS-A" Relationship: Method overriding is used when a subclass "IS-A" type of its superclass, indicating a specialization or refinement of the superclass behavior.

How to use:

Create a subclass that extends the superclass containing the method to be overridden.

Define a method in the subclass with the same signature (name, return type, and parameters) as the method in the superclass.

Add the @Override annotation to ensure that the method is indeed intended to override a superclass method. While not mandatory, it helps prevent accidental mistakes.

The subclass method must have the same or more permissive access modifier as the superclass method.

Example:

class Shape {

    public void draw() {

        System.out.println("Drawing a shape");

    }

}

class Circle extends Shape {

    @Override

    public void draw() {

        System.out.println("Drawing a circle");

    }

}

// Using method overriding

Shape shape = new Circle(); // Polymorphic assignment

shape.draw(); // Output: "Drawing a circle"

In the above example, the Shape class has a method called draw(), and the Circle class extends the Shape class. The Circle class overrides the draw() method with its specific implementation. When we create an object of the Circle class and invoke the draw() method through the Shape reference, the overridden method in the Circle class is executed, demonstrating polymorphism.

Remember the following points when using method overriding:

The method in the subclass must have the same method signature (name, return type, and parameters) as the method in the superclass.
The subclass method must be declared with the @Override annotation to indicate that it is intended to override a superclass method.
The subclass method can have a more permissive access modifier (e.g., public) but not a more restrictive one (e.g., private).
Method overriding is useful when you want to provide a specialized implementation of a method in a subclass while maintaining a common interface with the superclass. It promotes code reuse, flexibility, and follows the principles of inheritance and polymorphism.

Friday, July 7, 2023

Method overloading in JAVA

Method overloading in Java allows you to define multiple methods with the same name but different parameter lists within a class. Each overloaded method performs a similar operation but with different inputs or variations. Here's an overview of when and how to use method overloading in Java:

Purpose:

Enhance Readability: Method overloading improves code readability by using the same method name for similar operations. It allows developers to use descriptive method names without worrying about conflicts.

Flexibility: Overloaded methods provide flexibility by accepting different types or numbers of arguments. This allows users to invoke methods with different parameter combinations based on their requirements.

Code Reusability: Overloaded methods enable code reuse as they encapsulate similar behavior in a single method name.

How to use:

Define multiple methods within a class with the same name but different parameter lists (number, type, or order of parameters).

The methods must have different parameter signatures to distinguish them during compilation.

The return type of the method can be the same or different.

Method overloading is not possible by changing only the return type.

Example:

public class Calculator {

    public int add(int a, int b) {

        return a + b;

    }

    public double add(double a, double b) {

        return a + b;

    }

    public int add(int a, int b, int c) {

        return a + b + c;

    }

}

// Using the overloaded methods

Calculator calculator = new Calculator();

int result1 = calculator.add(2, 3);

double result2 = calculator.add(2.5, 3.5);

int result3 = calculator.add(2, 3, 4);

System.out.println(result1); // Output: 5

System.out.println(result2); // Output: 6.0

System.out.println(result3); // Output: 9

In the above example, the Calculator class has multiple add methods with different parameter lists. The first add method accepts two integers, the second add method accepts two doubles, and the third add method accepts three integers. Depending on the argument types used, the appropriate method is invoked.

Remember the following points when using method overloading:

Method overloading is determined at compile-time based on the method signature.
The return type alone is not sufficient to distinguish between overloaded methods.
It's important to consider parameter types, their order, and the number of parameters to differentiate between overloaded methods.
Method overloading provides flexibility and improves code readability by allowing multiple methods with the same name but different parameter lists. It's a useful technique to handle similar operations with variations in inputs or behaviors.

Tuesday, July 4, 2023

Garbage Collection in JAVA

Garbage collection in Java is an automatic memory management process that frees up memory by identifying and disposing of objects that are no longer in use. The purpose of garbage collection is to prevent memory leaks and optimize memory usage in Java programs. Here's an overview of garbage collection in Java and a sample program:

Purpose:

Memory Management: Garbage collection automatically releases memory occupied by objects that are no longer reachable, freeing up resources.

Eliminating Manual Memory Deallocation: Garbage collection removes the need for manual memory deallocation, reducing the risk of memory leaks and programming errors.

Simplifying Memory Management: Developers can focus on writing code rather than explicitly managing memory, leading to increased productivity and reduced maintenance effort.

How to use:

Garbage collection in Java is performed by the Java Virtual Machine (JVM) automatically.

Developers do not have direct control over the garbage collection process.

The JVM uses various algorithms to determine which objects are eligible for garbage collection based on reachability analysis.

Sample Program:

public class GarbageCollectionExample {

    public static void main(String[] args) {

        // Create an object

        MyClass myObject = new MyClass();

        // Nullify the reference to the object

        myObject = null;

        // Request garbage collection (optional)

        System.gc();

        // Other program logic...

    }

}

class MyClass {

    // Constructor

    public MyClass() {

        System.out.println("MyClass object created");

    }

    // Override finalize() method (optional)

    @Override

    protected void finalize() throws Throwable {

        System.out.println("MyClass object garbage collected");

    }

}

In the above program, we create an instance of the MyClass class. After nullifying the reference to the object, we can optionally request garbage collection using System.gc(). The finalize() method, which is invoked by the garbage collector before an object is collected, can be overridden to perform any necessary cleanup operations.

Note: It's important to understand that while we can request garbage collection using System.gc(), the JVM decides when and how garbage collection is performed. In most cases, manual intervention is not required, and the JVM handles garbage collection efficiently.

Remember that garbage collection is an automatic process in Java, and explicit memory deallocation is not necessary. It's crucial to design your programs in a way that allows objects to be eligible for garbage collection when they are no longer needed.

Monday, July 3, 2023

Static and Non-Static methods in JAVA

In Java, the decision to use static or non-static methods depends on the context and requirements of your program. Let's explore the purpose of static and non-static methods and how to use them in Java:

Static Methods:

Purpose: Static methods belong to the class rather than an instance of the class. They can be accessed without creating an object of the class. Static methods are typically used for utility methods or operations that don't require instance-specific data.

How to use:

Declare a static method using the static keyword.

Access a static method using the class name, followed by the method name.

Static methods can only directly access other static members (variables or methods) of the class.

Static methods cannot use the this keyword since they don't have access to instance-specific data.

Example:

public class MathUtils {

    public static int add(int a, int b) {

        return a + b;

    }

}

// Calling a static method

int result = MathUtils.add(3, 5);

System.out.println(result); 

Output: 8

Non-Static Methods:
Purpose: Non-static methods are associated with instances of a class. They can access and manipulate instance-specific data and are commonly used for object-specific operations or behaviors.

How to use:
Non-static methods are declared without the static keyword.
Non-static methods can access both static and non-static members of the class directly.
To call a non-static method, you need to create an object of the class and access the method through that object.

Example:
public class Circle {
    private double radius;
    public void setRadius(double radius) {
        this.radius = radius;
    }
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}
// Using non-static methods
Circle myCircle = new Circle();
myCircle.setRadius(5.0);
double area = myCircle.calculateArea();
System.out.println(area); 

Output: 78.53981633974483

Remember that the choice between static and non-static methods depends on the specific requirements and design of your program. Static methods provide utility or shared functionality, while non-static methods are used for object-specific operations.

Sunday, July 2, 2023

LinkedHashMap in JAVA

In Java, LinkedHashMap is a class that extends the HashMap class and provides a predictable iteration order based on the insertion order of elements. Here's when and why you would use a LinkedHashMap:

Maintaining insertion order: Unlike HashMap, LinkedHashMap maintains the order in which elements are inserted into the map. It provides a predictable iteration order, which can be useful when you need to iterate over the map's elements in the order they were added.

Access-ordered iteration: LinkedHashMap also supports access-ordered iteration in addition to insertion order. With access-ordered mode enabled, the most recently accessed elements are moved to the end of the iteration order. This can be beneficial in scenarios where you frequently access and modify elements, and you want to prioritize recently accessed elements for efficient retrieval.

Iteration performance: LinkedHashMap provides faster iteration performance compared to TreeMap (which maintains a sorted order) since it doesn't require the overhead of maintaining a sorted structure.

Compatibility with existing APIs: LinkedHashMap is compatible with the Map interface and can be used wherever a Map is expected. This makes it a suitable choice when you want to maintain insertion order and leverage the functionality provided by the Map interface.

Here's an example of how to use LinkedHashMap in Java:

import java.util.LinkedHashMap;

import java.util.Map;

public class LinkedHashMapExample {

    public static void main(String[] args) {

        // Create a LinkedHashMap

        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();

        // Add elements to the LinkedHashMap

        linkedHashMap.put(3, "Apple");

        linkedHashMap.put(2, "Banana");

        linkedHashMap.put(1, "Orange");

        // Iterate over the LinkedHashMap

        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

    }

}

In this example, we create a LinkedHashMap called linkedHashMap that maps integers to strings.

We add elements to the LinkedHashMap using the put() method. The elements are added in a specific order.

We iterate over the LinkedHashMap using the entrySet() method, which provides a set view of the mappings. The iteration order is based on the insertion order.

Output:
3: Apple
2: Banana
1: Orange

As shown in the example, LinkedHashMap maintains the order of elements based on their insertion order. This can be useful when you need to preserve the order in which elements were added to the map.

Saturday, July 1, 2023

Convert String to different cases in JAVA

In Java, you can convert a String to different cases, such as lowercase or uppercase, using the following methods:

Converting to lowercase:

Using the toLowerCase() method: String lowercaseString = originalString.toLowerCase();

Converting to uppercase:

Using the toUpperCase() method: String uppercaseString = originalString.toUpperCase();

Here's an example that demonstrates how to convert a String to different cases:

public class StringCaseConversionExample {

    public static void main(String[] args) {

        String originalString = "Hello, World!";

        String lowercaseString = originalString.toLowerCase();

        System.out.println("Lowercase: " + lowercaseString);

        String uppercaseString = originalString.toUpperCase();

        System.out.println("Uppercase: " + uppercaseString);

    }

}

Output:
Lowercase: hello, world!
Uppercase: HELLO, WORLD!

In this example, we have an originalString that contains the text "Hello, World!".

We convert the originalString to lowercase using the toLowerCase() method and store it in the lowercaseString variable.

We convert the originalString to uppercase using the toUpperCase() method and store it in the uppercaseString variable.

The resulting lowercase and uppercase strings are printed to the console.

These methods are useful when you need to standardize the case of strings for comparison, formatting, or other purposes.

Saturday, June 24, 2023

Convert String to different data types in JAVA

In Java, you can convert a String to different data types using various methods provided by the respective wrapper classes or built-in conversion methods. Here are some common data types and their conversion methods:

Converting to Integer:

  • Using Integer.parseInt() method: int intValue = Integer.parseInt(stringValue);
  • Using Integer.valueOf() method: Integer intValue = Integer.valueOf(stringValue);

Converting to Double:

  • Using Double.parseDouble() method: double doubleValue = Double.parseDouble(stringValue);
  • Using Double.valueOf() method: Double doubleValue = Double.valueOf(stringValue);

Converting to Boolean:

  • Using Boolean.parseBoolean() method: boolean booleanValue = Boolean.parseBoolean(stringValue);
  • Using Boolean.valueOf() method: Boolean booleanValue = Boolean.valueOf(stringValue);

Converting to Character:

  • Getting the first character of the string: char charValue = stringValue.charAt(0);

Converting to Long:

  • Using Long.parseLong() method: long longValue = Long.parseLong(stringValue);
  • Using Long.valueOf() method: Long longValue = Long.valueOf(stringValue);

Note that when converting to numeric types (Integer, Double, Long), if the String cannot be parsed into a valid number format, it will throw a NumberFormatException. For converting to Boolean, the string is considered true if it equals ignoring case "true" or "1"; otherwise, it is considered false.

Here's an example that demonstrates how to convert a String to different data types:

public class StringConversionExample {

    public static void main(String[] args) {

        String intValueString = "123";

        int intValue = Integer.parseInt(intValueString);

        System.out.println("Converted Integer value: " + intValue);


        String doubleValueString = "3.14";

        double doubleValue = Double.parseDouble(doubleValueString);

        System.out.println("Converted Double value: " + doubleValue);


        String booleanValueString = "true";

        boolean booleanValue = Boolean.parseBoolean(booleanValueString);

        System.out.println("Converted Boolean value: " + booleanValue);


        String charValueString = "A";

        char charValue = charValueString.charAt(0);

        System.out.println("Converted Character value: " + charValue);


        String longValueString = "9876543210";

        long longValue = Long.parseLong(longValueString);

        System.out.println("Converted Long value: " + longValue);

    }

}

Output:
Converted Integer value: 123
Converted Double value: 3.14
Converted Boolean value: true
Converted Character value: A
Converted Long value: 9876543210

In this example, we convert different String values to Integer, Double, Boolean, Character, and Long data types using their respective conversion methods.

Make sure to handle exceptions appropriately, such as NumberFormatException, when performing string-to-numeric conversions to handle invalid input gracefully.

Friday, June 23, 2023

Print Prime number in JAVA

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and itself.

Here's an example code in Java to print prime numbers up to a given limit:

public class PrimeNumbers {

    public static void main(String[] args) {

        int limit = 100; // Define the limit

        System.out.println("Prime numbers up to " + limit + ":");

        for (int number = 2; number <= limit; number++) {

            if (isPrime(number)) {

                System.out.print(number + " ");

            }

        }

    }

    // Check if a number is prime

    public static boolean isPrime(int number) {

        if (number <= 1) {

            return false;

        }

        for (int divisor = 2; divisor <= Math.sqrt(number); divisor++) {

            if (number % divisor == 0) {

                return false;

            }

        }

        return true;

    }

}

In this example, we set the limit variable to 100, which determines the range of numbers to check for primality.
We iterate over each number from 2 to the given limit.
Inside the loop, we call the isPrime() method to check if the current number is prime.
The isPrime() method checks if the number is less than or equal to 1 and returns false. Otherwise, it iterates from 2 up to the square root of the number to check for any divisors. If a divisor is found, the method returns false, indicating that the number is not prime. If no divisor is found, the method returns true, indicating that the number is prime.

Prime numbers are printed to the console.

Output:
Prime numbers up to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

The program prints all prime numbers from 2 to the specified limit (100 in this case). The isPrime() method is used to determine whether a number is prime or not by checking for divisors.

Thursday, June 22, 2023

ArrayList in JAVA

In Java, ArrayList is a class that implements the List interface and provides a resizable array-based implementation of a dynamic array. It allows you to store and manipulate elements in a flexible manner. Here's when and why you would use an ArrayList:

Dynamic size: Unlike regular arrays, ArrayList provides dynamic resizing, allowing you to add or remove elements at runtime without worrying about the fixed size of the array. It automatically adjusts its size as elements are added or removed.

Random access: ArrayList supports random access to elements, meaning you can retrieve elements by their index. This allows for efficient and fast retrieval of elements at a specific position.

Collection manipulation: ArrayList provides various methods for manipulating the collection, such as adding elements, removing elements, replacing elements, and checking for the presence of elements. It also supports iterating over the elements using enhanced for loops or iterators.

Compatibility with other APIs: ArrayList is widely used and is compatible with many Java APIs and frameworks. It is often used as a common data structure to exchange and manipulate data between different parts of an application.

Here's an example of how to use ArrayList in Java:

import java.util.ArrayList;

import java.util.List;

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList

        List<String> fruits = new ArrayList<>();

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Orange");

        // Access elements by index

        String firstFruit = fruits.get(0);

        System.out.println("First fruit: " + firstFruit); // Output: Apple

        // Iterate over the ArrayList

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

        // Output: Apple, Banana, Orange

        // Remove an element

        fruits.remove("Banana");

        // Check if an element exists

        boolean containsOrange = fruits.contains("Orange");

        System.out.println("Contains Orange? " + containsOrange); // Output: true

        // Get the size of the ArrayList

        int size = fruits.size();

        System.out.println("Size of ArrayList: " + size); // Output: 2

    }

}

In this example, we create an ArrayList called fruits that stores String elements.

We add elements to the ArrayList using the add() method.

We retrieve an element by its index using the get() method.

We iterate over the ArrayList using a for-each loop and print the elements.

We remove an element using the remove() method.

We check if an element exists using the contains() method.

We get the size of the ArrayList using the size() method.

Output:
First fruit: Apple
Apple
Banana
Orange
Contains Orange? true
Size of ArrayList: 2

As shown in the example, ArrayList provides a flexible and convenient way to store and manipulate elements in Java. It offers dynamic resizing, random access to elements, and various methods for element manipulation, making it a commonly used data structure in Java programming.