Java Access Modifiers and OOP Concepts
Java Access Modifiers and OOP Concepts
1. Access modifiers in Java help to restrict the scope of a 1. The ArrayList class is a resizable array, which can be
class, constructor, variable, method, or data member. found in the [Link] package.
2. Types of Access Modifiers: Default, Private, Protected 2. ArrayList<String> cars = new ArrayList<String>();
and Public. 3. Sort an arraylist: [Link](arraylist name);
What are the various types of Classes in Java? What is a Java Constructor?
1. Static, Final, Abstract, Concrete and Singleton Class. 1. A constructor in Java is a special method that is used to
initialize objects.
What is Singleton Class in Java? 2. The constructor’s name must match the class name and
1. In object-oriented programming, a singleton class is a class cannot have a return type (like void).
that can have only one object (an instance of the class) at a 3. The constructor is called when the object is created.
time. 4. Types of Constructors: Default and Parameterized.
A
Java OOPs Concepts: What is Java Super Keyword?
1. Inheritance: it is a mechanism in java by which one class 1. The super keyword refers to superclass (parent) objects.
is allowed to inherit the features (fields and methods) of 2. It is used to call superclass methods, and to access the
another class. superclass constructor.
2. Encapsulation: it is a process of wrapping code and data What is Java this Keyword?
together into a single unit, for example, a capsule which is
mixed of several medicines. The public setXXX() and 1. This keyword refers to the current object in a method or
getXXX() methods are the access points of the instance constructor.
V 3.
variables of the EncapTest class.
Abstraction: it is the process of hiding certain details and
showing only essential information to the users. In java,
abstraction is achieved by interfaces and abstract
classes.
2. The most common use of this keyword is to eliminate the
confusion between class attributes and parameters with the
same name (because a class attribute is shadowed by a
method or constructor parameter).
4. Polymorphism: it means having many forms. Using What is the Final Keyword in Java?
polymorphism, we can perform a single action in different 1. The final keyword in java is used to restrict the user. The
ways. It could be achieved by method overloading and java final keyword can be used in many contexts. The
overriding (Runtime Polymorphism). Final can be:
a. Variable: If you make any variable as final, you
JA
1. Java array is an object which contains elements of a similar What is the difference between Throw and Throws keywords in
data type. Java?
2. int Array = new int[20];
3. int[][] intArray = new int[10][20];
1. Throw: Java throw keyword is used throw an exception 2. Here, keys are unique identifiers used to associate each
explicitly in the code, inside the function or the block of value on a map.
code. Throw is used within the method. 3. It allows one null for key and multiple nulls for values.
4. It uses put method to insert a new element.
2. Throws: Java throws keyword is used in the method
signature to declare an exception which might be thrown What is Hash Table?
by the function while the execution of the code. Throws is 5. It stores elements in key/value pairs, and it uses put
used with the method signature. method to insert a new element.
1. It does not allow null for key as well as for value.
What is finalize() method in Java?
What is Hash Set?
1. The finalize() method is used just before object is
destroyed and can be called just prior to object creation. 1. It does not allow duplicates.
2. It can have a single null value. It uses add method.
A
What are Java Wrapper Classes? What is the difference between [Link]() and
1. Wrapper classes provide a way to use primitive data types [Link]()?
(int, boolean, etc..) as objects. 1. parseInt(): will be returning the primitive type int.
2. ArrayList<Integer> myNumbers = new 2. valueOf(): will be returning the Integer wrapper Object.
ArrayList<Integer>();
Java Program to “Sort an Array”:
Can We Override Static Method in Java? If not, Why?
1. public class Main {
1. No, we cannot override static methods because methods 2. public static void main(String[] args) {
overriding is based on dynamic binding at runtime and the 3. //define original array
V static methods are bonded using static binding at compile
time. So, we cannot override static methods.
5.
6.
int [] intArray = new int []
{52,45,32,64,12,87,78,98,23,7};
int temp = 0;
//print original array
1. The Collection in Java is a framework that provides an 7. [Link]("Original array: ");
architecture to store and manipulate the group of objects. 8. for (int i = 0; i <[Link]; i++) {
2. Java Collection means a single unit of objects. Java 9. [Link](intArray[i] + " ");
Collection framework provides many interfaces (Set, List, 10. }
Queue, Deque) and classes (ArrayList, Vector, LinkedList, 11. //Sort the array in ascending order using two for loops
JA
A
10. { Java program to “Extract a word from a string”:
11. ch= [Link](i); //extracts each character
12. nstr= ch+nstr; //adds each character in front of the 1. import [Link];
existing string 2. public class string {
13. } 3. public static void main(String args[]){
14. [Link]("Reversed word: "+ nstr); 4. Scanner sc = new Scanner([Link]);
15. }} 5. String sentence = "This is a bird";
6. [Link]("Enter a word to extract from the
Java Program to “Reverse any String”: string: ");
7. String wordToextract = [Link]();
V 1.
2.
3.
4.
5.
class ReverseString {
public static void main(String[] args)
{
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
8.
9.
10.
11.
if([Link](wordToextract)){
int y = [Link](wordToextract);
[Link](y);
String u = [Link](y ,
6. [Link](input); y+([Link]()));
7. [Link](); 12. [Link](u);
8. [Link](input1); }} 13. } }}
A
6. char string[] = [Link]();
7. [Link]("Duplicate characters in a given
string: ");
8. //Counts each character present in the string
9. for(int i = 0; i <[Link]; i++) {
10. count = 1;
11. for(int j = i+1; j <[Link]; j++) {
12. if(string[i] == string[j] && string[i] != ' ') {
13. count++;
14. //Set string[j] to 0 to avoid printing visited
V 15.
16.
17.
character
}}
string[j] = '0';
XPath Axes for Dynamic XPath In Selenium: How to perform double click in Selenium?
1. ancestor 1. Actions act = new Actions(driver);
2. ancestor-or-self 2. WebElement ele = [Link]([Link]("XPath of
3. descendant the element"));
4. descendant-or-self 3. [Link](ele).perform();
5. preceding sibling
6. following-sibling How to click on an element which is not clickable in Selenium?
7. parent
8. child 1. WebElement element =
9. following [Link]([Link]("Login"));
10. preceding 2. Actions act = new Actions(driver);
11. Examples: 3. [Link](element).click().build().perform();
a. //label[text()='Email']/following-sibling::input[1]
How to perform SHIFT+CTRL+S in Selenium?
b. //td[text()='Maria
Anders']/preceding-sibling::td/child::input 1. Actions act = new Actions(driver);
c. //label[text()='Email']/following-sibling::input[1]/ 2. [Link]([Link]).keyDown([Link]).s
parent::div endKeys("s").build().perform();
d. //div[@class='container']/child::input[@type='text
'] How to Drag and Drop in Selenium?
e. //div[@class='container']/descendant::button
1. Actions act = new Actions(driver);
f. //div[@class='buttons']/ancestor-or-self::div
g. //label[text()='Password']/following::input[1]
2. Action dragAndDrop = 1. TakesScreenshot scrShot =((TakesScreenshot)webdriver);
[Link](fromElement).moveToElement(toEleme 2. File SrcFile=[Link]([Link]);
nt).release(toElement).build(); 3. File DestFile=new File(fileWithPath);
3. [Link](); 4. [Link](SrcFile, DestFile);
How to handle Sliders in Selenium? How to handle multiple windows/multiple popups in Selenium?
Why POM?
1. Easy to Maintain
2. Easy Readability of Scripts
3. Reduce duplicacy
4. Re-usability
5. Reliability
What is Cucumber?
What is the file extension of all the Gherkin files? 1. Scenario Outline uses the Example Keyword to define the
test data for the Scenario. This works for the whole test.
1. .feature a. Examples:
In Cucumber, comments are denoted by b. | username | password |
c. | testuser_1 | Test@153 |
1. # 2. Data Table does not use the Example Keyword. This works
only for a single step.
Enlist the files needed in the Cucumber framework. a. And User enters Credentials to LogIn
1. Feature File (.feature): It has plain text descriptions of b. | testuser_1 | Test@153 |
single or numerous test situations. What are Maps in Data Tables?
2. Step Definition File (.java): It has the extension .java. It
essentially acts as a translator between the test scenario 1. Maps in Data Tables can be used in different ways.
steps provided in the feature file and the automation code. Headers can also be defined for the data tables. The same
3. TestRunner (.java): .java is the file extension for this file. step can be executed multiple times with a different set of
It connects the feature file and the step definition file. No test data using Maps.
code should be written under the TestRunner class.
a. @RunWith([Link]) What are the tags in Cucumber?
b. @CucumberOptions(features="Features",glue={" 1. In Cucumber, tags are used to associate a test like smoke,
StepDefinition"}) regression etc. with a particular scenario.
c. public class Runner {} a. @SmokeTest
In a feature file, what is the maximum number of scenarios? b. Scenario: Search contact
c. Given: The desired contact will be displayed
1. A feature file in Cucumber can include a maximum of 10 2. Test Runner File: tags = {"@SmokeTest"}) // RUN all
scenarios. SmokeTest Cases.
How to run multiple feature files using the Cucumber runner How to ignore the test cases of a particular tag in Cucumber?
class?
1. tags = {"~@SmokeTest"} // ignores the SmokeTest Cases
1. features="src/test/resources/FeatureFiles",tags="@feature1
scenariogroup1,@feature2cenariogroup2" What are hooks in Cucumber?
How can Cucumber be integrated with Selenium WebDriver? 1. Hooks are code blocks that execute before or after each
Cucumber scenario in the execution cycle. Hooks are
1. [Link] defined in the step definition file.
2. [Link]
3. [Link] What is the Background Keyword in Cucumber?
4. [Link] 1. Background in Cucumber is used to define a step or series
5. [Link] of steps that are common to all the tests in the feature file.
6. [Link] 2. It is defined in the feature file.
What is a Web Service? 1. Free
2. Easy
1. It is a service offered by an electronic device to another 3. APIs Support
electronic device, communicating with each other via the 4. Extensible
World Wide Web. Or
2. It is a server running on a computer device, listening for What is a collection in Postman?
requests at a particular port over a network, serving web
documents (HTML, JSON, XML, images). 1. A collection in Postman helps to group similar requests. It
helps in systematically arranging the requests into folders.
What are the types of API Testing?
How can we stop executing requests or stop the collection run?
1. Unit Testing
2. Functional Testing 1. [Link](null);
3. Load Testing What are Variables in Postman?
4. Security Testing
5. Penetration Testing 1. Variables enable you to store and reuse values in Postman.
What are the protocols used in API Testing? How will you log variable values in Postman?
What is the difference between REST and SOAP? How do you access postman variables?
Why Postman?
How to write Test Case in Postman? OR How response codes g. Oauth 2.0: you first retrieve an access token for
are validated in Postman? the API, then use that token to authenticate future
requests.
It can be done using assertion in Postman.
What is Client URL (cURL)?
1. [Link]("Status code is 200", function () {
2. [Link](200); 1. cURL, which stands for client URL, is a command line
3. }); tool that developers use to transfer data to and from a
a. [Link]() is a closure function that allows you to server.
write tests for a Postman request that’s being 2. It supports about 22 protocols, including HTTP.
executed. 3. This combination makes it a very good ad-hoc tool for
b. [Link](200) is the actual testing our REST services.
assertion that is trying to validate the response to
have a status code of 200. What is the Web Services Description Language (WSDL)?
What are the basic requirements for writing Appium tests? How to initialize Appium Driver?
1. [Link]()
Using Selenium for cross-browser testing offers benefits such as broad browser compatibility (Chrome, Firefox, Safari, etc.), the ability to run tests concurrently across different browsers, and integration with other testing frameworks like TestNG. However, drawbacks include potential inconsistencies between browsers due to rendering or JavaScript engine differences, as well as challenges in managing browser-specific scripts and handling browser updates automatically. Despite these challenges, Selenium remains a robust tool when allied with proper testing strategies .
The Automation Testing Life Cycle (ATLC) enhances test efficiency and effectiveness by establishing a systematic process that covers evaluating automation feasibility, selecting suitable tools, planning, scripting, executing tests, and maintaining them. By providing a structured approach, ATLC ensures that automation meets business requirements, optimally utilizes resources, and aligns with the broader testing and development strategies, leading to reliable and scalable test automation solutions .
TestNG enhances testing in Selenium by offering capabilities such as parallel execution, HTML report generation, and more complex annotations, making it more flexible and scalable than JUnit. It facilitates grouping, prioritization of tests, and supports data-driven testing, allowing for sophisticated test suite management and execution strategies .
A HashMap in Java allows for one null key and multiple null values within its entries, utilizing a hashing mechanism to organize key/value pairs efficiently. Conversely, a HashTable strictly prohibits null keys and values, as it was designed to prevent storage of non-existent value types, ensuring that all interactions involve non-null data which maintains consistent performance .
Maven Lifecycle phases structure the build processes in a Java project effectively by organizing tasks like validation, compilation, testing, packaging, integration testing, and deployment. Each phase serves a critical purpose—such as checking the project structure in 'validate', compiling source code in 'compile', and creating deliverable artifacts in 'package'. This sequential execution not only streamlines the development workflow but also ensures consistency and quality control at every stage .
The Page Object Model (POM) in Selenium is a design pattern that promotes easy maintainability, readability, and reusability by encapsulating page elements and actions within a class structure. Integrating OOP concepts, POM uses abstraction to hide web element locators, encapsulation to initialize and manage page objects privately, and inheritance to utilize a base class for initialization. Method overloading and overriding are also utilized to enhance flexibility and functionality within page interactions .
In Java, HashMap allows storing elements in key/value pairs where keys are unique identifiers, supporting one null key and multiple null values. In contrast, HashTable does not permit null keys or values. HashSet is designed to store only unique elements, allowing a single null value and preventing duplicates .
XPath axes in Selenium are a set of axes used to find elements in relation to the current context node through a path expression. They enable precise retrieval of elements even in dynamic pages, supporting axes such as ancestor, descendant, following-sibling, and preceding-sibling. These axes help navigate complex XML or HTML documents by defining relationships such as hierarchy or sibling connections to efficiently locate or test specific nodes or elements .
The Java Collection framework provides an architecture to store and manipulate a group of objects as a single unit, which is fundamental for efficient data management. Interfaces such as Set, List, Queue, and Deque define the core operations, specifying how different types of collections should operate. Classes like ArrayList, HashSet, and others offer implementations of these interfaces, delivering various functionalities such as duplicate management (e.g., List allows duplicates, whereas Set doesn't) and order maintenance (e.g., LinkedList maintains order, whereas HashSet doesn't).
StringBuilder should be used when constructing a mutable sequence of characters where thread safety is not a concern, as it offers better performance due to the lack of synchronization. In scenarios where multiple threads might access the string concurrently, StringBuffer would be preferable because it's synchronized and hence thread-safe. A String, which is immutable, is best used in operations where constants need to be represented or when the content is not expected to change .