Q11. How do you merge two sorted arrays in Java?
Explanation:
This logic is similar to the merge process in merge sort. Use two pointers to compare and insert elements in a new array.
Code Example:
java
public class MergeSortedArrays {
public static int[] merge(int[] arr1, int[] arr2) {
int n1 = arr1.length, n2 = arr2.length;
int[] result = new int[n1 + n2];
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
result[k++] = (arr1[i] <= arr2[j]) ? arr1[i++] : arr2[j++];
}
while (i < n1) result[k++] = arr1[i++];
while (j < n2) result[k++] = arr2[j++];
return result;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8, 10};
System.out.println(“Merged: ” + java.util.Arrays.toString(merge(arr1, arr2)));
}
}
Output:
makefile
Merged: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Q12. How do you convert a List to Set and Set to List in Java?
Explanation:
- Convert List to Set to remove duplicates.
- Convert Set to List to regain indexing.
Code Example:
java
import java.util.*;
public class CollectionConverter {
public static void main(String[] args) {
List<String> names = Arrays.asList(“Alice”, “Bob”, “Alice”, “Charlie”);
Set<String> set = new HashSet<>(names);
List<String> uniqueList = new ArrayList<>(set);
System.out.println(“Original List: ” + names);
System.out.println(“Set (No Duplicates): ” + set);
System.out.println(“Back to List: ” + uniqueList);
}
}
Output:
mathematica
Original List: [Alice, Bob, Alice, Charlie]
Set (No Duplicates): [Bob, Alice, Charlie]
Back to List: [Bob, Alice, Charlie]
Q13. What are the uses of ArrayList, HashSet, and HashMap in Java?
Explanation:
- ArrayList: Maintains order and allows duplicates.
- HashSet: Unordered, no duplicates.
- HashMap: Key-value storage, fast lookup.
Code Example:
java
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList(“Apple”, “Banana”, “Apple”));
HashSet<String> set = new HashSet<>(list);
HashMap<String, Integer> map = new HashMap<>();
map.put(“Apple”, 5);
map.put(“Banana”, 3);
map.put(“Orange”, 2);
System.out.println(“ArrayList: ” + list);
System.out.println(“HashSet: ” + set);
System.out.println(“HashMap: ” + map);
System.out.println(“Apple Count: ” + map.get(“Apple”));
}
}
Output:
yaml
ArrayList: [Apple, Banana, Apple]
HashSet: [Apple, Banana]
HashMap: {Apple=5, Banana=3, Orange=2}
Apple Count: 5
Q14. How do you remove all white spaces from a string in Java?
Explanation:
You can use regex or character filtering with StringBuilder.
Code Example:
java
public class WhiteSpaceRemover {
public static String removeWhiteSpacesRegex(String input) {
return input.replaceAll(“\\s+”, “”);
}
public static String removeWhiteSpacesManual(String input) {
StringBuilder result = new StringBuilder();
for (char c : input.toCharArray()) {
if (!Character.isWhitespace(c)) result.append(c);
}
return result.toString();
}
public static void main(String[] args) {
String text = ” Java Programming is fun “;
System.out.println(removeWhiteSpacesRegex(text));
System.out.println(removeWhiteSpacesManual(text));
}
}
Output:
nginx
JavaProgrammingisfun
JavaProgrammingisfun
Q15. How to Extract Only Digits from an Alphanumeric String in Java?
Answer:
To extract digits from an alphanumeric string, you can use:
- Regex-based approach
- Character iteration with Character.isDigit()
Code Example:
java
public class DigitExtractor {
// Using regex
public static String extractDigitsRegex(String input) {
return input.replaceAll(“[^0-9]”, “”);
}
// Using manual method
public static String extractDigitsManual(String input) {
StringBuilder result = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String alphanumeric = “abc123def456ghi789”;
System.out.println(“Regex Output: ” + extractDigitsRegex(alphanumeric));
System.out.println(“Manual Output: ” + extractDigitsManual(alphanumeric));
}
}
Output:
yaml
Regex Output: 123456789
Manual Output: 123456789
Q16. How to Read Data from Excel in Java using Apache POI?
Answer:
Apache POI provides robust libraries to read .xls and .xlsx files in Java. Use the following jars:
- poi-5.2.3.jar
- poi-ooxml-5.2.3.jar
- commons-io-2.11.0.jar
Code Example:
java
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File(“data.xlsx”));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case STRING: System.out.print(cell.getStringCellValue() + “\t”); break;
case NUMERIC: System.out.print(cell.getNumericCellValue() + “\t”); break;
case BOOLEAN: System.out.print(cell.getBooleanCellValue() + “\t”); break;
default: System.out.print(“\t”);
}
}
System.out.println();
}
workbook.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Q17. How to Capture a Screenshot in Selenium using Java?
Answer:
Selenium provides the TakesScreenshot interface to capture screenshots of web pages during test execution.
Code Example:
java
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
public class ScreenshotCapture {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get(“https://www.example.com”);
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(“screenshot.png”));
System.out.println(“Screenshot saved successfully.”);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Q18. How to Implement Implicit, Explicit, and Fluent Waits in Selenium?
Answer:
Selenium provides three wait mechanisms:
- Implicit Wait – waits globally for element availability.
- Explicit Wait – waits for specific conditions.
- Fluent Wait – customizable wait with polling and exceptions.
Code Example:
java
WebDriver driver = new ChromeDriver();
// Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
WebElement explicitElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“someId”)));
// Fluent Wait
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement fluentElement = fluentWait.until(driver1 -> driver1.findElement(By.id(“dynamicElement”)));
Q19. How to Find All Broken Links on a Webpage using Selenium Java?
Answer:
To find broken links:
- Collect all <a> tag hrefs.
- Use HttpURLConnection to send HEAD requests.
- Check response code (>= 400 means broken).
Code Example:
java
List<WebElement> links = driver.findElements(By.tagName(“a”));
for (WebElement link : links) {
String url = link.getAttribute(“href”);
if (url != null && url.startsWith(“http”)) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(“HEAD”);
conn.connect();
int statusCode = conn.getResponseCode();
if (statusCode >= 400) {
System.out.println(“Broken link: ” + url + ” – Code: ” + statusCode);
}
}
}
Q20. How to Count Total Web Elements (Links, Images, Buttons) on a Webpage?
Answer:
You can count specific elements using driver.findElements(By.tagName(“tag”)).
Code Example:
java
WebDriver driver = new ChromeDriver();
driver.get(“https://www.example.com”);
int linkCount = driver.findElements(By.tagName(“a”)).size();
int imageCount = driver.findElements(By.tagName(“img”)).size();
int buttonCount = driver.findElements(By.tagName(“button”)).size();
System.out.println(“Links: ” + linkCount);
System.out.println(“Images: ” + imageCount);
System.out.println(“Buttons: ” + buttonCount);
👉The Next 20 Questions -3: JAVA STRING