Home page

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); 
     
}

Wednesday, August 9, 2023

Selenium waits comparison

Selenium Waits Comparison

Wait Type Description Usage Advantages Disadvantages
Implicit Wait Waits for a certain time before throwing an exception if an element is not immediately available. driver.manage().timeouts().implicitlyWait(time, unit); Simplifies test code, applies globally. May cause unnecessary waiting, not precise.
Explicit Wait Waits for a specific condition to be satisfied before proceeding. WebDriverWait + ExpectedConditions Precise control, better for dynamic elements. More code, may need to handle various exceptions.
Fluent Wait Combines implicit and explicit waits, polling at specified intervals. Wait + polling + ignored exceptions Flexible, customizable wait conditions. Complex syntax, requires exception handling.
Thread.sleep() Pauses the execution for a specified amount of time. Thread.sleep(milliseconds); Simple to use. Not recommended, fixed wait time.

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.