Highlighting an element in Selenium can be useful for debugging purposes. It visually distinguishes the element being interacted with. This small addition can improve debugging, make demo videos clearer, and reduce false positives in your test results.
In Selenium Java, you can achieve this by using JavaScript. You can alter the element’s style, such as adding a border around it.
In the below example, we want to highlight the text – English.
Below is the Selenium program that will highlight the text.
package Web;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.time.Duration;
public class HighlightText_Example {
public static void main(String args[]) {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
try {
driver.get("https://www.selenium.dev/");
// identify the element
WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));
// Optionally, we wait to observe the element before changing the color
Thread.sleep(1000);
// Set the background color to yellow and the border to red
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);
// Optionally, we can wait to observe the highlight effect
Thread.sleep(2000);
System.out.println("Text is highlighted");
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
// Closing browser
driver.quit();
}
}
}
The output of the above program is
Below is the image of yellow highlighted background with red border.
Explanation:
1. Set Up Chrome Options and WebDriver
ChromeOptionsis created. A ChromeDriverobject driveris created to control the Chrome browser. implicitlyWaitis set to 10 seconds to wait for elements to be present before throwing an exception. The browser window is maximized for better visibility during the test.
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
2. Navigate to a Webpage
The get()method of driveris used to navigate to the specified URL.
driver.get("https://www.selenium.dev/");
3. Find Element
An element is located using an XPath expression.
WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));
4. Execute JavaScript
Use the JavaScriptExecutor to apply styling to the element. This can include adding a border or changing the background color temporarily.
// Set the background color to yellow and the border to red
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);
5. Pause for visualization
This is an optional step. We have added it so that the user can see the color change.
Thread.sleep(2000);
6. Clean Up
The finallyblock ensures that the browser is closed irrespective of whether the test passes or fails, using driver.quit() to close all browser windows and end the session.
// Close the browser
driver.quit();
Summary: 1. Initialize a WebDriver and direct it to interact with your target webpage. 2. Identify the desired web element using suitable locators. 3. By using arguments[0].style.border=’3px solid red’, you can add a red border around the element, effectively highlighting it.
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Retrieving font properties using Selenium in Java is essential for testing and validating the styling of web applications. We can verify font-related CSS attributes such as font-family, font-size, and font-weight and so on. This ensures that your application’s user interface adheres to design specifications. It provides a consistent user experience across different browsers and environments.
To find the font properties of a web element in Selenium (Java), use the getCssValue method. We will use the getCssValueto extract properties of font like font-family, font-size, and many more.
In the below example, we want to find the font properties of the highlighted text, that is “LEARN MORE”.
Below is the Selenium program that find the font properties of the highlighted text.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.IOException;
import java.time.Duration;
public class Font_Example {
public static void main(String args[]) throws IOException {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.manage().window().maximize();
try {
// Navigate to Url
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.xpath("//*[@class='selenium-button-container']/a"));
// Retrieve the font color
String fontFamily = element.getCssValue("font-family");
System.out.println("fontFamily : " + fontFamily );
// Retrieve the font size
String fontSize = element.getCssValue("font-size");
System.out.println("fontSize : " + fontSize);
// Retrieve the font weight
String fontWeight = element.getCssValue("font-weight");
System.out.println("fontWeight : " + fontWeight);
// Retrieve the font style
String fontStyle = element.getCssValue("font-style");
System.out.println("fontStyle : " + fontStyle);
// Retrieve the font variation
String fontVariant = element.getCssValue("font-variant");
System.out.println("fontVariant : " + fontVariant);
// Retrieve the line height
String lineHeight = element.getCssValue("line-height");
System.out.println("lineHeight : " + lineHeight);
// Retrieve the letter spacing
String letterSpacing = element.getCssValue("letter-spacing");
System.out.println("letterSpacing : " + letterSpacing);
// Retrieve the text transform
String textTransform = element.getCssValue("text-transform");
System.out.println("textTransform : " + textTransform);
// Retrieve the text decoration
String textDecoration = element.getCssValue("text-decoration");
System.out.println("textDecoration : " + textDecoration);
System.out.println("####################### Verify the font properties #########################");
// Verify the font family
if (fontFamily.contains("Arial")) {
System.out.println("fontFamily is as expected.");
} else {
System.out.println("fontFamily is not as expected. Found: " + fontFamily);
}
// Verify the font size
if (fontSize.equals("16px")) {
System.out.println("fontSize is as expected.");
} else {
System.out.println("fontSize is not as expected. Found: " + fontSize);
}
// Verify the font weight
if (fontWeight.equals("500")) {
System.out.println("fontWeight is as expected.");
} else {
System.out.println("fontWeight is not as expected. Found: " + fontWeight);
}
// Verify the font style
if (fontStyle.equals("italic")) {
System.out.println("fontStyle is as expected.");
} else {
System.out.println("fontStyle is not as expected. Found: " + fontStyle);
}
// Verify the font variant
if (fontVariant.equals("small-caps")) {
System.out.println("fontVariant is as expected.");
} else {
System.out.println("fontVariant is not as expected. Found: " + fontVariant);
}
// Verify the line height
if (lineHeight.equals("24px")) {
System.out.println("lineHeight is as expected.");
} else {
System.out.println("lineHeight is not as expected. Found: " + lineHeight);
}
// Verify the letter Spacing
if (letterSpacing.equals("normal")) {
System.out.println("letterSpacing is as expected.");
} else {
System.out.println("letterSpacing is not as expected. Found: " + letterSpacing);
}
// Verify the text Transform
if (textTransform.equals("lowercase")) {
System.out.println("textTransform is as expected.");
} else {
System.out.println("textTransform is not as expected. Found: " + textTransform);
}
// Verify the text Decoration
if (textDecoration.equals("underline")) {
System.out.println("textDecoration is as expected.");
} else {
System.out.println("textDecoration is not as expected. Found: " + textDecoration);
}
} finally {
// Close the browser
driver.quit();
}
}
}
The output of the above program is
Explanation:
1. Set Up Chrome Options and WebDriver
ChromeOptionsis created. A ChromeDriverobject driveris created to control the Chrome browser. implicitlyWaitis set to 5 seconds to wait for elements to be present before throwing an exception. The browser window is maximized for better visibility during the test.
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.manage().window().maximize();
2. Navigate to the Webpage
The get()method of driveris used to navigate to the specified URL.
driver.get("https://www.selenium.dev/");
3. Find Element
An element is located using an XPath expression that targets an anchor tag within a specific container class.
WebElement element = driver.findElement(By.xpath("//*[@class='selenium-button-container']/a"));
4. Retrieve and Print CSS Font Properties
The script fetches various font-related CSS properties using getCssValue().
font-family – Specifies the typeface to be applied to the text. (e.g. Arial, Helvetica, sans-serif)
font-size – Determines the size of the font displayed in the element. (e.g. 16px)
font-weight – Defines the weight (or thickness) of the font.(e.g. 100, 200, 400, 700)
font-style – Applies styles such as italics to the text. (e.g. normal, italic, oblique)
font-variant – Adjusts the appearance of text for typographic effects(e.g. small-caps, normal)
line-height – Controls the vertical space between lines of text. (e.g. 24px)
letter-spacing – Adjusts the space between individual letters. (e.g. normal)
text-transform – Modifies the capitalization of text. (e.g. uppercase, lowercase, capitalize)
text-decoration – Applies decorative lines to text. (e.g. underline, strikethrough)
// Retrieve the font color
String fontFamily = element.getCssValue("font-family");
System.out.println("fontFamily : " + fontFamily );
// Retrieve the font size
String fontSize = element.getCssValue("font-size");
System.out.println("fontSize : " + fontSize);
// Retrieve the font weight
String fontWeight = element.getCssValue("font-weight");
System.out.println("fontWeight : " + fontWeight);
// Retrieve the font style
String fontStyle = element.getCssValue("font-style");
System.out.println("fontStyle : " + fontStyle);
// Retrieve the font variation
String fontVariant = element.getCssValue("font-variant");
System.out.println("fontVariant : " + fontVariant);
// Retrieve the line height
String lineHeight = element.getCssValue("line-height");
System.out.println("lineHeight : " + lineHeight);
// Retrieve the letter spacing
String letterSpacing = element.getCssValue("letter-spacing");
System.out.println("letterSpacing : " + letterSpacing);
// Retrieve the text transform
String textTransform = element.getCssValue("text-transform");
System.out.println("textTransform : " + textTransform);
// Retrieve the text decoration
String textDecoration = element.getCssValue("text-decoration");
System.out.println("textDecoration : " + textDecoration);
5. Verification of CSS Properties
Each retrieved property is compared against expected values with individual checks. It prints corresponding messages based on whether the actual properties match the expected ones.
// Verify the font family
if (fontFamily.contains("Arial")) {
System.out.println("fontFamily is as expected.");
} else {
System.out.println("fontFamily is not as expected. Found: " + fontFamily);
}
// Verify the font size
if (fontSize.equals("16px")) {
System.out.println("fontSize is as expected.");
} else {
System.out.println("fontSize is not as expected. Found: " + fontSize);
}
// Verify the font weight
if (fontWeight.equals("500")) {
System.out.println("fontWeight is as expected.");
} else {
System.out.println("fontWeight is not as expected. Found: " + fontWeight);
}
// Verify the font style
if (fontStyle.equals("italic")) {
System.out.println("fontStyle is as expected.");
} else {
System.out.println("fontStyle is not as expected. Found: " + fontStyle);
}
// Verify the font variant
if (fontVariant.equals("small-caps")) {
System.out.println("fontVariant is as expected.");
} else {
System.out.println("fontVariant is not as expected. Found: " + fontVariant);
}
// Verify the line height
if (lineHeight.equals("24px")) {
System.out.println("lineHeight is as expected.");
} else {
System.out.println("lineHeight is not as expected. Found: " + lineHeight);
}
// Verify the letter Spacing
if (letterSpacing.equals("normal")) {
System.out.println("letterSpacing is as expected.");
} else {
System.out.println("letterSpacing is not as expected. Found: " + letterSpacing);
}
// Verify the text Transform
if (textTransform.equals("lowercase")) {
System.out.println("textTransform is as expected.");
} else {
System.out.println("textTransform is not as expected. Found: " + textTransform);
}
// Verify the text Decoration
if (textDecoration.equals("underline")) {
System.out.println("textDecoration is as expected.");
} else {
System.out.println("textDecoration is not as expected. Found: " + textDecoration);
}
6. Clean Up
The finallyblock ensures that the browser is closed irrespective of whether the test passes or fails, using driver.quit() to close all browser windows and end the session.
// Close the browser
driver.quit();
Summary: 1. Initialize a WebDriver and direct it to interact with your target webpage. 2. Identify the desired web element using suitable locators. 3. Retrieve and print out the CSS values for font attributes using getCssValue.
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
In the web development, user experience plays a crucial part. Testers should ensure that style guides are followed across different pages. They should also be applied consistently to components. Verifying that the colors on a web page match design specifications helps maintain brand consistency. It ensures that the user interface looks as intended. There are chances that colors render differently across browsers and devices. Testing across different environments ensures that no matter where the website is accessed, the experience remains consistent.
To find the text color and background color of a web element in Selenium (Java), use the “getCssValue” method. Use “color” for the text color. Use “background-color” for the background color. You can convert the result to HEX using
org.openqa.selenium.support.Color.
Find Text color
In the below example, we want to find the text color of the highlighted text.
Below is the Selenium program that find the text color and match it with the expected color.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.Color;
import java.io.IOException;
import java.time.Duration;
public class Color_Example {
public static void main(String args[]) throws IOException {
String expectedColor = "#ffffff"; // White color in HEX
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
try {
// Navigate to Url
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.id("dev-partners"));
// Retrieve the font color CSS property as RGBA
String rgbaColor = element.getCssValue("color");
System.out.println("rgbaColor : " + rgbaColor);
// Convert the RGBA color to hex using the Color class
String hexColor = Color.fromString(rgbaColor).asHex();
System.out.println("hexColor : " + hexColor);
// Convert the RGBA color to RGB using the Color class
String rgbColor = Color.fromString(rgbaColor).asRgb();
System.out.println("rgbColor : " + rgbColor);
// Verify the color (example: verifying against expected #ffffff color)
if (hexColor.equals(expectedColor)) {
System.out.println("Hex color is as expected.");
} else {
System.out.println("Hex color is not as expected. Found: " + hexColor);
}
} finally {
// Close the browser
driver.quit();
}
}
}
The output of the above program is
Explanation:
1.Define Expected Color
Variable expectedColoris defined to hold the expected hexadecimal color value (`#ffffff`, representing white).
String expectedColor = "#ffffff"; // White color in HEX
2. Set Up Chrome Options and WebDriver
ChromeOptionsis created. A ChromeDriverobject driveris created to control the Chrome browser. implicitlyWaitis set to 10 seconds to wait for elements to be present before throwing an exception. The browser window is maximized for better visibility during the test.
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
3. Navigate to a Webpage
The get() method of driveris used to navigate to the specified URL.
driver.get("https://www.selenium.dev/");
4. Find Element and Retrieve CSS Property
The element is located by the specified id, “dev-partners”. The getCssValuemethod retrieves the color of the element in RGBA format.
WebElement element = driver.findElement(By.id("dev-partners"));
// Retrieve the font color CSS property as RGBA
String rgbaColor = element.getCssValue("color");
System.out.println("rgbaColor : " + rgbaColor);
5. Convert Color Formats
RGBA to Hex: `Color.fromString(rgbaColor).asHex()` converts the RGBA color to hexadecimal format. RGBA to RGB: `Color.fromString(rgbaColor).asRgb()` converts the RGBA color to RGB format for additional representation.
// Convert the RGBA color to hex using the Color class
String hexColor = Color.fromString(rgbaColor).asHex();
System.out.println("hexColor : " + hexColor);
// Convert the RGBA color to RGB using the Color class
String rgbColor = Color.fromString(rgbaColor).asRgb();
System.out.println("rgbColor : " + rgbColor);
6. Verify Color
The hexadecimal color of the element is compared with expectedColor. If they match, it prints a confirmation message. If they do not match, it prints a message indicating the color did not match the expected value.
// Verify the color (example: verifying against expected #ffffff color)
if (hexColor.equals(expectedColor)) {
System.out.println("Hex color is as expected.");
} else {
System.out.println("Hex color is not as expected. Found: " + hexColor);
}
7. Clean Up
The finallyblock ensures that the browser is closed irrespective of whether the test passes or fails, using driver.quit()to close all browser windows and end the session.
// Close the browser
driver.quit();
Find Background color
If we want to find the background color, then use the below command:
getCssValue("background-color")
Below is an example to find the background color.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.Color;
import java.io.IOException;
import java.time.Duration;
public class BackgroundColor_Example {
public static void main(String args[]) throws IOException {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
try {
// Navigate to Url
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.id("dev-partners"));
// Retrieve the background color CSS property
String bgColorValue = element.getCssValue("background-color");
System.out.println("color : " + bgColorValue);
// Convert the background color to HEX format
String hexColor = Color.fromString(bgColorValue).asHex();
System.out.println("hexColor : " + hexColor);
// Convert the background color to RGB format
String rgbColor = Color.fromString(bgColorValue).asRgb();
System.out.println("rgbColor : " + rgbColor);
// Verify the color (example: verifying against expected #43b02a color)
String expectedColor = "#43b02a"; // Green color in HEX
if (hexColor.equals(expectedColor)) {
System.out.println("Background color is as expected.");
} else {
System.out.println("Background color is not as expected. Found: " + hexColor);
}
} finally {
// Close the browser
driver.quit();
}
}
}
The output of the above program is
Summary: 1. Initialize a WebDriver and direct it to interact with your target webpage. 2. Identify the desired web element using suitable locators. 3. Retrieve and print out the CSS values for text and background colors using getCssValue.
Welcome to the Performance Testing Quiz! This blog post features 25 multiple-choice questions that explore basic concepts of Performance Testing.
1. What is the primary goal of performance testing?
a) To identify issues in navigation flow b) To ensure that an application performs well under expected load c) To validate user interface design d) To test security vulnerabilities
Answer 1
b) To ensure that an application performs well under expected load
Performance testing evaluates how an application behaves under expected or stress conditions to ensure it meets performance criteria.
2. Which tool is commonly used for Performance Testing?
a) Selenium b) Apache JMeter c) Visual Studio Code d) Postman
Answer 2
b) Apache JMeter
Apache JMeter is a popular open-source tool for performing load and performance testing.
3. What is Throughput in Performance Testing?
Choose one option
a) Number of lines of code executed b) Response time of the system c) Number of transactions processed in a given timeframe d) Number of errors per second
Answer 3
c) Number of transactions processed in a given timeframe
Throughput measures the number of transactions or requests processed in a given period.
4. What type of performance testing aims to find out how a system operates under heavy loads?
Choose one option
a) Load Testing b) Stress Testing c) Soak Testing d) Security Testing
Answer 4
c) Stress Testing
Stress testing determines how a system performs under peak or extreme conditions, beyond normal operational capacity.
5. What is the main objective of load testing?
a) To break the system b) To evaluate software scalability c) To test the system’s reaction under varying traffic loads d) To check system breaches
Answer 5
c) To test the system’s reaction under varying traffic loads
Load testing evaluates how a software application behaves when it is subjected to varying loads, usually simulating multiple users.
6. Performance Testing is a type of
Choose one option
a) Functional Testing b) Non-Functional Testing c) Security Testing d) None of the above
Answer 6
b) Non-Functional Testing
7. Performance is concerned with achieving ………………… that meet the performance objectives for the project or product
Choose one option
a) Response times, Throughput, and Stress levels b) Response times, Throughput, and Resource-utilization levels c) Reason times, Throughput, and Resource-utilization levels d) Response times, Click-through, and Resource-utilization levels
Answer 7
b) Response times, Throughput, and Resource-utilization levels
8. What is Spike Testing in Performance Testing?
Choose one option
a) Sudden large increases in system load b) Gradually increasing system load c) Reducing system performance d) Testing system updates
Answer 8
a) Sudden large increases in system load
Spike testing measures how a system reacts to sudden and significant increases in load.
9. What is endurance testing?
a) Testing the system’s ability to handle high traffic during peak hours b) Testing the system’s compatibility with different operating systems c) Testing the system’s performance under normal conditions d) Testing the system’s ability to handle an increasing load over an extended period
Answer 9
d) Testing the system’s ability to handle an increasing load over an extended period
Endurance testing involves testing a system over a prolonged period to determine its ability to perform under sustained load without performance degradation.
10. What is the purpose of a baseline test in performance testing?
a) To test under maximum load b) To establish a benchmark for future tests c) To identify security issues d) To simulate network failures
Answer 10
b) To establish a benchmark for future tests
11. What is transaction response time?
Choose one option
a) Time to write transaction b) Time to complete entire business transaction c) Time to start transaction d) Time to log transaction
Answer 11
b) Time to complete entire business transaction
12. Which of the following is NOT a goal of performance testing?
Choose one option
a) Detecting memory leakage b) Determining system sustainability c) Evaluating error handling d) Reducing hardware requirements
Answer 12
d) Reducing hardware requirements
13. What does KPI stand for in the context of performance testing?
Choose one option
a) Key Performance Indicator b) Knowledge Program Initiative c) Key Process Integration d) Kernel Performance Index
Answer 13
a) Key Performance Indicator
14. When should performance testing be conducted?
Choose one option
a) Only after code changes b) Regularly throughout the development lifecycle c) After production deployment d) Only during the initial phases of development
Answer 14
b) Regularly throughout the development lifecycle
15. Which of the following can impact performance testing results?
Choose one option
a) Developer skill levels b) Network capacity and configuration c) HR policies d) Office location
Answer 15
b) Network capacity and configuration
16. What does ‘Think Time’ refer to in Load Testing?
Choose one option
a) The delay between user actions b) Time required for machine learning predictions c) AI decision-making time d) Load balancing wait time
Answer 16
a) The delay between user actions
17. What is the primary concern of resource utilization testing?
Choose one option
a) Adequate electricity supply b) Efficient use of time during testing c) The impact of an application on system resources d) Cost of the software tools
Answer 17
c) The impact of an application on system resources
18. What does ‘concurrency’ refer to in performance testing?
a) Parallel software development processes b) Simultaneous execution of multiple tasks c) Single user testing multiple features d) Continuous testing cycles
Answer 18
b) Simultaneous execution of multiple tasks
19. Which of the following is true about cloud performance testing?
a) It is more cost-effective than traditional methods b) It cannot simulate real-world traffic c) It requires dedicated on-premise hardware d) It doesn’t support network latency measurements
Answer 19
a) It is more cost-effective than traditional methods
20. Which metric is used to measure the speed at which a system returns to a steady state after a particular load?
Choose one option
a) Response time b) Throughput c) Recovery time d) Load time
Answer 20
c) Recovery time
21. Which factors impact system performance during Performance Testing?
Choose one option
a) Only font sizes and text placement b) Browser color schemes and UI themes c) User location and screen resolution d) CPU, Memory, Database, Network latency
Answer 21
d) CPU, Memory, Database, Network latency
22. Which of the following is not a type of performance test?
Choose one option
a) Endurance testing b) Load testing c) Compatibility testing d) Stress testing
Answer 22
c) Compatibility testing
23. Performance Testing environment should be scaled at least up to 50% of the production environment?
Choose one option
a) Yes b) No
Answer 23
a) Yes
24. Which metric is NOT typically measured in performance testing?
a) Response time b) Throughput c) Code coverage d) Resource utilization
Answer 24
c) Code coverage
25. What is steady state in performance testing?
a) System startup phase b) Period of constant load c) System shutdown phase d) Error state
Answer 25
b) Period of constant load
We would love to hear from you! Please leave your comments and share your scores in the section below
An XML file contains data between the tags. This makes it complex to read compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:
In this article, we will discuss how to create a XML document using Java DOM parser. There is another tutorial to read XML – How to read XML using Java DOM Parser.
Java DOM parser API has methods, interfaces and classes to create XML documents. Using this API, we can create XML documents from the scratch through our Java applications. The createElement() method creates new elements and the appendChild() method appends the created elements to already existing elements.
Below is the sample XML which is created and saved in resources/Payloads as output.xml.
The complete program looks like as shown below:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import javax.xml.transform.OutputKeys;
public class CreateXMLDocument {
public static void main(String[] args) {
try {
// Step 1: Create a DocumentBuilderFactory and DocumentBuilder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Step 2: Create a new Document
Document document = builder.newDocument();
// Step 3: Create and append root element
Element root = document.createElement("employees");
document.appendChild(root);
// Step 4: Create and append employee elements
Element employee1 = document.createElement("employee");
employee1.setAttribute("id", "1");
Element name1 = document.createElement("Name");
name1.appendChild(document.createTextNode("Jimmy Buffet"));
Element id1 = document.createElement("Employee_Id");
id1.appendChild(document.createTextNode(String.valueOf(10342256)));
Element salary1 = document.createElement("Salary");
salary1.appendChild(document.createTextNode(String.valueOf(5000.00)));
employee1.appendChild(name1);
employee1.appendChild(id1);
employee1.appendChild(salary1);
root.appendChild(employee1);
Element employee2 = document.createElement("employee");
employee2.setAttribute("id", "2");
Element name2 = document.createElement("name");
name2.appendChild(document.createTextNode("Jane Smith"));
Element position2 = document.createElement("position");
position2.appendChild(document.createTextNode("Project Manager"));
employee2.appendChild(name2);
employee2.appendChild(position2);
root.appendChild(employee2);
// Step 5: Write the content into an XML file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(document);
// Write XML to file
StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/output.xml"));
transformer.transform(domSource, fileResult);
// Print XML to console
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult);
System.out.println("XML file created successfully!");
} catch (ParserConfigurationException | TransformerException e) {
e.printStackTrace();
}
}
}
The output of the above program is
Explanation
1. Creating a DocumentBuilder Object
It has ‘newDocumentBuilder()’ method that creates an instance of the class ‘DocumentBuilder’. This DocumentBuilder class is used to get input in the form of streams, files, URLs and SAX InputSources.
Using DocumentBuilder object created in the above step, create a new document with newDocument()function.
Document document = builder.newDocument();
3. Creating the root element
Every XML document should possess a single root element , which is also called a parent element. We can create the root element using createElement() method and append it to the document created in the previous step.
Element root = document.createElement("employees");
document.appendChild(root);
4. Appending elements to the root element
Inside the root element, we can create any number of child elements. We append them the same way we appended the root element to the document.
To write text content inside an element, we can use createTextNode() method.
We can also create attributes for elements using createAttribute() method.
Element employee1 = document.createElement("employee");
employee1.setAttribute("id", "1");
Element name1 = document.createElement("Name");
name1.appendChild(document.createTextNode("Jimmy Buffet"));
Element id1 = document.createElement("Employee_Id");
id1.appendChild(document.createTextNode(String.valueOf(10342256)));
Element salary1 = document.createElement("Salary");
salary1.appendChild(document.createTextNode(String.valueOf(5000.00)));
employee1.appendChild(name1);
employee1.appendChild(id1);
employee1.appendChild(salary1);
root.appendChild(employee1);
Element employee2 = document.createElement("employee");
employee2.setAttribute("id", "2");
Element name2 = document.createElement("name");
name2.appendChild(document.createTextNode("Jane Smith"));
Element position2 = document.createElement("position");
position2.appendChild(document.createTextNode("Project Manager"));
employee2.appendChild(name2);
employee2.appendChild(position2);
root.appendChild(employee2);
5. Writing the content into XML file
After building the elements inside the document with their corresponding attributes, we must write this content into an XML file. We do this by creating a Transformer object, which transforms our source document into StreamResult. It then stores the result in the specified file path with the given name.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(document);
// Write XML to file
StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/output.xml"));
transformer.transform(domSource, fileResult);
6. Printing the output on the console
We can test our XML file by printing it on the console. This is an optional step.
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult);
Summary:
1. DocumentBuilderFactory and DocumentBuilder: These are used for creating new DOM `Document` instances. 2. Document Object:Represents the XML in memory, and methods like `createElement()` and `createTextNode()` are used to build the XML structure. 3. Transformer: Converts the DOM representation to a file. 4. StreamResult: Used to specify the output file where the XML content will be written.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
An XML file contains data between the tags. This makes it complex to read compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:
DOM stands for Document Object Model. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser. It is a little slow when compared to SAX. It occupies more space when loaded into memory. We can insert and delete nodes using the DOM API.
How to retrieve tag name from XML?
Below is the sample JSON which is used as an example . I have saved this file in resources/Payloads as SimpleXML.xml.
package XML.DOM;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class XMLParserTagNameExample {
public static void main(String[] args) {
try {
// Create a DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Obtain a DocumentBuilder from the factory
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse the XML file into a Document
Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));
// Normalize XML structure
document.getDocumentElement().normalize();
// Get the root element
Element root = document.getDocumentElement();
System.out.println("Root Element: " + root.getNodeName());
System.out.println("-----------------------");
// Retrieve the first employee element for extracting tag names
NodeList nodeList = document.getElementsByTagName("employee");
if (nodeList.getLength() > 0) {
// If there is at least one employee, use it to print the element and attribute names
Element employee = (Element) nodeList.item(0);
// Print the tag names
System.out.println("Employee ID Attribute Name: id");
System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
System.out.println("-----------------------");
}
} catch (ParserConfigurationException e) {
System.out.println("Parser configuration error occurred: " + e.getMessage());
} catch (SAXException e) {
System.out.println("SAX parsing error occurred: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO error when loading XML file: " + e.getMessage());
} finally {
System.out.println("XML parsing operation completed.");
}
}
}
The output of the above program is
Explanation
1. Creating a DocumentBuilder Object
It has ‘newDocumentBuilder()’ method that creates an instance of the class ‘DocumentBuilder’. This DocumentBuilder class is used to get input in the form of streams, files, URLs and SAX InputSources.
DocumentBuilder created in above steps is used to parse the input XML file. It contains a method named parse() which accepts a file or input stream as a parameter and returns a DOM Document object. If the given file or input stream is NULL, this method throws an IllegalArgumentException.
The `normalize` method is called on the document’s root element. This step ensures that the XML structure is uniform, often by merging adjacent text nodes and removing empty ones.
document.getDocumentElement().normalize();
4. Get root node
We can use getDocumentElement() to get the root node and the element of the XML file.
Element root = document.getDocumentElement();
System.out.println("Root Element: " + root.getNodeName());
System.out.println("-----------------------");
5. Retrieving Root Element Name
A `NodeList` containing all elements with the tag name `employee` is obtained using `getElementsByTagName`. This list can be used to iterate over all employee entries in the XML.
NodeList nodeList = document.getElementsByTagName("employee");
if (nodeList.getLength() > 0) {
// If there is at least one employee, use it to print the element and attribute names
Element employee = (Element) nodeList.item(0);
// Print the tag names
System.out.println("Employee ID Attribute Name: id");
System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
System.out.println("-----------------------");
}
}
getTagName() returns the name of the root element in the form of a string. Retrieve the first employee element for extracting tag names and print the tag names.
getNodeName() is used to get the name of the node. It returns the node name in the form of a string.
6. Implement Exception Handling
The program catches `ParserConfigurationException`, `SAXException`, and `IOException`, addressing specific issues that might occur during parsing. Each exception type is followed by a custom message that explains the nature of the error. At the end, a message is printed to confirm the completion of the XML parsing operation by using finally block.
The program loops through each node in the `NodeList`. Each node is checked if it is an `ELEMENT_NODE`. For each valid employee element, it extracts: – Attribute: The `id` attribute value using `getAttribute(“id”)`. – Text Content: The contents of child elements “name” and “position” using `getElementsByTagName(“name”).item(0).getTextContent()` and similarly for “position”.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element employee = (Element) node;
// Get the attribute and text content
String id = employee.getAttribute("id");
String name = employee.getElementsByTagName("name").item(0).getTextContent();
String position = employee.getElementsByTagName("position").item(0).getTextContent();
System.out.println("Employee ID: " + id);
System.out.println("Name: " + name);
System.out.println("Position: " + position);
System.out.println("-----------------------");
}
}
}
getTextContent() is used to get the text content of elements.
7. Implement Exception Handling
This is same as the step 6 of the above program.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
The JSON-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using a Java program.
JSON.simple is available at the Central Maven Repository. Maven users add this to the POM.
import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;
import java.io.FileWriter;
import java.io.IOException;
public class WriteSimpleJson {
public static void main(String[] args) {
// JSON String
JsonObject jsonObject = new JsonObject();
jsonObject.put("Name", "Vibha");
jsonObject.put("Salary", 4500.00);
// JSON Array
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
jsonObject.put("Working Days", list);
System.out.println(Jsoner.serialize(jsonObject));
try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
Jsoner.serialize(jsonObject, fileWriter);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
The output of the above program is
Explanation
1. Creating a JSON Object
A `JsonObject` named `jsonObject` is created to hold data. Using `put()`, the code adds a “Name” field with the value “Vibha” and a “Salary” field with the value `4500.00` to the JSON object.
JsonObject jsonObject = new JsonObject();
jsonObject.put("Name", "Vibha");
jsonObject.put("Salary", 4500.00);
2. Creating a JSON Array
A `JsonArray` named `list` is created to contain multiple values. The days “Monday”, “Tuesday”, and “Wednesday” are added to the `list`. The JSON array list is added to the jsonObject under the key “Working Days”.
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
jsonObject.put("Working Days", list);
3. Writing JSON to a File
A FileWriter is used to open the file src/test/resources/Payloads/Employee.json for writing. The Jsoner.serialize() method serializes the jsonObject and writes it to the file, capturing the constructed JSON structure.
try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
Jsoner.serialize(jsonObject, fileWriter);
}
Write Complex JSON to File using JSON.simple
Below is the complex JSON which will be generated.
import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;
import java.io.FileWriter;
import java.io.IOException;
public class WriteComplexJson {
public static void main(String[] args) {
JsonObject jsonObject = new JsonObject();
//Name
JsonObject name = new JsonObject();
name.put("Forename", "Vibha");
name.put("Surname", "Singh");
jsonObject.put("Name", name);
//Salary
JsonObject salary = new JsonObject();
salary.put("Fixed", 4000.00);
//Bonus
JsonObject bonus = new JsonObject();
bonus.put("Monthly", 45.00);
bonus.put("Quaterly", 125.00);
bonus.put("Yearly", 500.00);
salary.put("Bonus", bonus);
jsonObject.put("Salary", salary);
// JSON Array
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
jsonObject.put("Working Days", list);
System.out.println(Jsoner.serialize(jsonObject));
try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/EmployeeDetails.json")) {
Jsoner.serialize(jsonObject, fileWriter);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
The output of the above program is
I have saved this file in resources/Payloads as EmployeeDetails.json.
Explanation
1.Creating JSON Objects
Serves as the root JSON object to encapsulate all the other JSON objects and arrays
JsonObject jsonObject = new JsonObject();
2. Name Object
A JsonObjectnamed name is created. It contains two properties: “Forename” with the value “Vibha” and “Surname” with the value “Singh”. This nameobject is then added to the root jsonObjectunder the key “Name”.
JsonObject name = new JsonObject();
name.put("Forename", "Vibha");
name.put("Surname", "Singh");
jsonObject.put("Name", name);
3. Salary Object
A `JsonObject` named `salary` is created with a property “Fixed” representing a fixed salary amount of 4000.00.
//Salary
JsonObject salary = new JsonObject();
salary.put("Fixed", 4000.00);
4. Bonus Object
A `JsonObject` named `bonus` is created. It contains properties for different types of bonuses: “Monthly” (45.00), “Quarterly” (125.00), and “Yearly” (500.00).
The `bonus` object is then added as a property of the `salary` object under the key “Bonus”.
The complete `salary` object, now including the bonus details, is added to the root `jsonObject` under the key “Salary”.
A `JsonArray` named `list` is created to represent the working days. The days “Monday”, “Tuesday”, and “Wednesday” are added to this array. This `list` is added to the root `jsonObject` under the key “Working Days”.
// JSON Array
JsonArray list = new JsonArray();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
jsonObject.put("Working Days", list);
6. Serialization of JSON
The entire `jsonObject` is serialized using `Jsoner.serialize()` and printed to the console, which converts the Java JSON structure into a JSON string.
The `try-with-resources` statement is used to ensure the `FileWriter` is closed automatically. A `FileWriter` writes the serialized JSON object to a file at `src/test/resources/Payloads/EmployeeDetails.json`.
try (FileWriter fileWriter = new FileWriter("src/test/resources/Payloads/Employee.json")) {
Jsoner.serialize(jsonObject, fileWriter); }
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Welcome to the Java Quiz! This blog post features 25 multiple-choice questions that explore the concepts of Arrays in Java.
1. What is an array in Java?
a) A data structure that can hold elements of different types b) A class that allows storing single data type elements in a contiguous memory location c) A collection of elements in no specific order d) A method for sorting elements
Answer 1
b) A class that allows storing single data type elements in a contiguous memory location
Arrays in Java are used to store multiple values of the same data type in a contiguous memory location.
2. How do you instantiate an array of integers with 10 elements in Java?
a) int[] arr = new int[10]; b) int arr = new int(10); c) int arr[10] = new int[]; d) int(10) arr = new int[];
Answer 2
a) int[] arr = new int[10];
3. What is the default value of an element in an int array in Java?
Choose one option
a) 1 b) 0 c) null d) Undefined
Answer 3
b) 0
In Java, arrays of primitive types like int are initialized to their default values. The default value for int is 0
4. What will be the output of the following Java program?
class array_output
{
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
When an array is declared using new operator then all of its elements are initialized to 0 automatically. for loop body is executed 5 times as whenever controls comes in the loop i value is incremented twice, first by i++ in body of loop then by ++i in increment condition of for loop.
5. What is the maximum number of dimensions an array can have in Java?
a) 1 b) 255 c) 2 d) No theoretical limit
Answer 5
b) 255
Java allows arrays to have up to 255 dimensions.
6. What will be the output of the following Java program?
public class array_output {
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = 'i';
System.out.print(array_variable[i] + "");
}
}
}
Choose one option
a) 1 2 3 4 5 6 7 8 9 10 b) 0 1 2 3 4 5 6 7 8 9 10 c) i j k l m n o p q r d) i i i i i i i i i i
Answer 6
d) i i i i i i i i i i
When an array is declared using the new operator, all of its elements are automatically initialized to default values—0 for numeric types, null for reference types, and ‘\0’ (null character) for char.
7. What will be the output of the following Java program?
public class array_output {
public static void main(String args[])
{
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i < 6; ++i)
result = result + num[i];
System.out.print(result/6);
}
}
Choose one option
a) 16.34 b) 16.566666644 c) 16.46666666666667 d) 16.46666666666666
Answer 7
c) 16.46666666666667
8. What happens if you try to access an index of an array that is out of bounds?
Choose one option
a) Compile-time error b) Returns null c) Throws ArrayIndexOutOfBoundsException d) None of the above
Answer 8
c) Throws ArrayIndexOutOfBoundsException
9. How do you declare an array of strings?
a) String[] arr; b) String arr[]; c) String arr(); d) String arr{};
Answer 9
a) String[] arr;
This is the standard way of declaring an array of strings in Java.
10. Which of the following is a valid declaration and initialization of String array in Java
a) String[] names ={“Tim”,”Mark”,”Charlie”} b) String names[] ={“Tim”,”Mark”,”Charlie”} c) String[3] names ={“Tim”,”Mark”,”Charlie”} d) Both a) and b) e) Both a) and c)
Answer 10
d) Both a) and b)
String[3] names = {“Tim”, “Mark”, “Charlie”};` is incorrect because Java does not allow specifying the size of the array within square brackets during initialization in this manner.
11. What will be the output?
public class Test {
public static void main(String[] args) {
String[] arr = {"Java", "Python", "C++"};
System.out.println(arr[1]);
}
}
Choose one option
a) Java b) Python c) C++ d) Compilation error
Answer 11
b) Python
arr[1]accesses the second element of the array, which is “Python”.
12. Which of the following statements is true?
Choose one option
a) Arrays are immutable b) Arrays are objects c) Arrays store elements of any data type d) Arrays automatically grow
Answer 12
b) Arrays are objects
In Java, arrays are objects and are part of the java.lang package.
13. What is the primary use of the `System.arraycopy()` method in Java?
Choose one option
a) To copy one array to another b) To reverse an array c) To sort an array d) To find an element in an array
Answer 13
a) To copy one array to another
System.arraycopy() is used to copy elements from one array to another.
14. What is printed by the following code snippet?
public class Test {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[1]);
}
}
Choose one option
a) 0 b) null c) undefined d) Compilation error
Answer 14
a) 0
Integer arrays are initialized to 0 by default.
15. What will be the result of this program?
public class array_output {
public static void main(String args[])
{
int[] arr = {1, 2, 3, 4};
System.out.println(arr.length);
}
}
Choose one option
a) 0 b) 3 c) 4 d) Compilation error
Answer 15
c) 4
arr.lengthreturns the number of elements in the array, which is 4.
16. What exception is thrown by Java code when trying to store values in a sufficiently large dimension of an array but with the wrong data type?
Choose one option
a) ArrayIndexOutOfBoundsException b) IllegalArgumentException c) ClassCastException d) ArrayStoreException
Answer 16
d) ArrayStoreException
ArrayStoreException occurs when attempting to store incorrect types into arrays of object types.
17. Which of the following is not a valid way to declare a two-dimensional array in Java?
Choose one option
a) int[][] arr = new int[3][3]; b) int arr[][] = new int[3][3]; c) int[] arr = new int[3][]; d) int[][] arr = new int[][];
Answer 17
d) int[][] arr = new int[][];
Option D is invalid because while it declares a two-dimensional array, it does not specify the size of either dimension at the time of declaration.
18. What is the correct way to iterate over a Java array using an enhanced for loop?
a) for (int i : arr) b) for (int i = 0; i < arr.length; i++) c) for (arr : int i) d) for (arr i : int)
Answer 18
a) for (int i : arr)
The enhanced for loop in Java is written as for (type variable : array).
19. What will happen if you try to store a double value into an int array?
a) The value will be rounded b) The value will be truncated c) A ClassCastException will be thrown d) A compile-time error
Answer 19
d) A compile-time error
You cannot store a double value in an int array without explicit casting, leading to a compile-time error.
20. What is the output of the following code?
public class array_output {
public static void main(String args[])
{
int[] arr = {2, 4, 6, 8};
System.out.println(arr[arr.length]);
}
}
Choose one option
a) 8 b) 4 c) 0 d) ArrayIndexOutOfBoundsException
Answer 20
d) ArrayIndexOutOfBoundsException
Since array indices are 0-based, accessing arr[arr.length] is out of bounds. The valid indices for this array are from 0 to arr.length – 1.
21. What is the output of the following code?
public class array_output {
public static void main(String args[]) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
System.out.println(arr[2]);
}
}
Choose one option
a) 3 b) 6 c) 8 d) 10
Answer 21
b) 6
The loop multiplies each element by 2. Therefore, arr[2] becomes 3 * 2 = 6.
22. What will be the output of the below program?
public class array_output {
public static void main(String args[]) {
int[] arr = {10, 20, 30, 40};
System.out.println(arr[1] + arr[2]);
}
}
Choose one option
a) 30 b) 50 c) 60 d) 70
Answer 22
b) 50
arr[1] is 20 and arr[2] is 30, so the sum is 20 + 30 = 50.
23. Can you resize an array in Java after it is created?
Choose one option
a) Yes b) No
Answer 23
b) No
24. How can you access the element at the second row and third column of a two-dimensional array “matrix”?
a) matrix[3][2] b) matrix[2, 3] c) matrix[1][2] d) matrix[2:3]
Answer 24
c) matrix[1][2]
Array indexing starts at 0 in Java, so the second row is index 1, and the third column is index 2.
25. What will be the default value of the elements in a two-dimensional array of type `int[][]` in Java?
a) null b) 0 c) undefined d) Compilation error
Answer 25
b) 0
For arrays of primitive data types like int, the default value of the elements is 0.
We would love to hear from you! Please leave your comments and share your scores in the section below