Selenium is open source tool to test web application. Jmeter is open source performance testing tool. Selenium and Jmeter are very popular and commonly used tools. Selenium and Jmeter both required scripting knowledge.
Wednesday, May 29, 2024
Find first and last occurrence of the letter ‘s’ in samosa with index number
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
}
}
}
- In this example, we take an integer number (e.g., 12345) as input.
- The printReverseNumber method is used to print the digits of the number in reverse order.
- Inside the printReverseNumber method, we use a while loop that runs as long as num is greater than 0.
- In each iteration of the loop, we extract the last digit of num using the modulus operator (num % 10) and print it.
- We then remove the last digit from num by dividing it by 10 (num /= 10).
- The loop continues until all digits of the number are printed.
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();
}
}
}
}
}
- 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;
}
}
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);
}
}
- Using Bitwise XOR Operation:
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:
- 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.
- 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.
- 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:
- Define a constructor: Declare a method with the same name as the class. Constructors do not have a return type, not even void.
- Define parameterized constructors (optional): Constructors can accept parameters to initialize member variables based on the provided values.
- 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
}
}
- Constructors have the same name as the class and are called automatically when an object is created.
- Constructors do not have a return type, not even void.
- Constructors can be overloaded, allowing you to define different ways to create objects based on varying parameter lists.
- If you don't provide a constructor explicitly, a default constructor (with no parameters) is automatically created by the compiler.
- 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:
- Key-Value Mapping: The main purpose of using a HashMap is to store key-value pairs, where each key is unique within the map.
- 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).
- 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:
- Import the HashMap class: Before using HashMap, import the java.util.HashMap class.
- Create a HashMap instance: Instantiate a HashMap object, specifying the types for the key and value.
- Add key-value pairs: Use the put method to add key-value pairs to the HashMap.
- Retrieve values: Use the get method to retrieve values based on their keys.
- 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
}
}
- 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
}
}
- 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.
- TreeSet does not allow null elements. However, if a custom Comparator is used, it should be capable of handling null values.
- TreeSet provides efficient search operations due to the underlying binary search tree structure.
- The elements in a TreeSet are stored in sorted order, which allows for easy iteration in ascending or descending order.
- 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;
}
}
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"
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
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");
}
}
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
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());
}
}
}
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);
}
}
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);
}
}
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;
}
}
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
}
}