0% found this document useful (0 votes)
2K views1,399 pages

112 Manual Testing Interview Questions Answers 1656817516 2

The document provides answers to common manual testing interview questions. It defines key testing terms like software testing, quality assurance, quality control, verification and validation. It also describes different testing types like functional testing, non-functional testing, black box testing and white box testing. Additional topics covered include the software development life cycle, automation testing advantages and disadvantages, performance testing and test plan documentation.

Uploaded by

Anurag Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views1,399 pages

112 Manual Testing Interview Questions Answers 1656817516 2

The document provides answers to common manual testing interview questions. It defines key testing terms like software testing, quality assurance, quality control, verification and validation. It also describes different testing types like functional testing, non-functional testing, black box testing and white box testing. Additional topics covered include the software development life cycle, automation testing advantages and disadvantages, performance testing and test plan documentation.

Uploaded by

Anurag Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1399

GVPL Global

112 Manual Testing Interview Questions & Answers

Ques.1. what do you mean by Software Testing?

Ans. Software testing is the process of evaluating a system to check if it satisfies


its business requirements. It measures the overall quality of the system in terms
of attributes. Like – correctness, completeness, usability, performance, etc.

Basically, it is used for ensuring the quality of software to the stakeholders of


the application.

Ques.2. Why is testing required?


Ans. We need software testing for the following reasons-
1. Testing provides an assurance to the stakeholders that the product works as
intended.

2. Avoidable defects leaked to the end-user/customer without proper testing


adds a bad reputation to the development company.

3. Defects detected earlier phase of SDLC results in lesser cost and resource
utilization of correction.

4. Saves development time by detecting issues in an earlier phase of


development.

5. The testing team adds another dimension to the software development by


providing a different viewpoint to the product development process.

Ques.3. When should we stop testing?


Ans. Testing (both manual and automated) can be stopped when one or more
of the following conditions are met-

1. After test case execution – The testing phase can be stopped when one
complete cycle of test cases is executed after the last known bug fix with the
agreed-upon value of pass-percentage

2. Once the testing deadline is met – Testing can be stopped after deadlines
get met with no high priority issues left in the system.

3. Based on Mean Time Between Failure (MTBF) – MTBF is the time interval
between two inherent failures. Based on stakeholder’s decisions, if the MTBF is
quite large, one can stop the testing phase.

4. Based on code coverage value – The testing phase can be stopped when
the automated code coverage reaches a specific threshold value with sufficient
pass-percentage and no critical bug.

Ques.4. What is Quality Assurance and what are the different activities
involved in Quality assurance?

Ans. Quality assurance is a process-driven approach that checks if the process


of developing the product is correct and conforming to all the standards. It is
considered a preventive measure. This is because it identifies the weakness in
the process to build software. It involves activities like document review, test
case review, walk-throughs, inspection, etc.

Ques.5. What is Quality Control and what are the different types of
testing involved in QC.

Ans. Quality control is a product-driven approach that checks that the


developed product conforms to all the specified requirements. It is considered
a corrective measure as it tests the built product to find the defects. It involves
different types of testing like functional testing, performance testing, usability
testing, etc.

Ques.6. What is the difference between Verification and Validation?


Ans. Following are the major differences between verification and validation-
# Verification Validation
Verification is the process of evaluating the
different artifacts as well as the process of
software development. Validation is the process of validating that the
1. developed software product conforms to the
This is done in order to ensure that the product specified business requirements.
being developed will comply with the
standards.

It is a static process of analyzing the It involves dynamic testing of a software


2.
documents and not the actual end product. product by running it.

3. Verification is a process-oriented approach. Validation is a product-oriented approach.

Answers the question – “Are we building the Answers the question – “Are we building the
4.
product right?” right product?”

Errors found during verification require lesser Errors found during validation require more
5. cost/resources to get fixed as compared to be cost/resources. Later the error is discovered
found during the validation phase. higher is the cost to fix it.

Ques.7. What is SDLC.

Ans. SDLC stands for Software Development Life Cycle. It refers to all the
activities performed during software development – requirement gathering,
requirement analysis, designing, coding or implementation, testing,
deployment, and maintenance.
Ques.8. Explain the STLC – Software Testing life cycle.
Ans. The software testing life cycle refers to all the activities performed during
testing of a software product. The phases include-
• Requirement analysis and validation – In this phase, the requirements
documents are analyzed and validated and the scope of testing is
defined.
• Test planning – In this phase, test plan strategy is defined, estimation of
test effort is defined along with automation strategy, and tool selection
is done.
• Test Design and Analysis – Here, test cases are designed, test data is
prepared and automation scripts are implemented.
• Test environment setup – A test environment closely simulating the
real-world environment is prepared.
• Test execution – The test cases are prepared, bugs are reported and
retested once resolved.
• Test closure and reporting – A test closure report is prepared to have
the final test results summary, learning, and test metrics.

Ques.9. What are the different types of testing.

Ans. Testing can broadly be defined into two types-


• Functional testing – Functional testing involves validating the
functional specifications of the system.
• Non Functional testing – Non-functional testing is a type of testing that
involves testing of non-functional requirements of the system such as
performance, scalability, security, endurance, portability, etc.
Going by the way the testing is done, it can be categorized as-

• Black box testing – In black-box testing, the tester need not have any
knowledge of the internal architecture or implementation of the system.
The tester interacts with the system through the interface providing input
and validating the received output.

• White box testing – In white box testing, the tester analyses the internal
architecture of the system as well as the quality of source code on
different parameters like code optimization, code coverage, reusability,
etc.

• Gray box testing – In gray box testing, the tester has partial access to the
internal architecture of the system e.g. the tester may have access to the
design documents or database structure. This information helps the tester
to test the application better.

Ques.10. What is manual testing.

Ans. Manual testing a type of testing that involves validation of the


requirements of the application by executing a predefined set of test cases
manually without the use of any automation tool.

Ques.11. What is automation testing?


Ans. Automation testing is a type of software testing that involves automated
test case execution using an automation tool. It helps in reducing the test
execution time as the test scripts written once, can be run automatically any
number of times without any human intervention.

Ques.12. What are some advantages of automation testing.


Ans. Some advantages of automation testing are-
1. Test execution using automation is fast and saves a considerable amount
of time.
2. Carefully written test scripts remove the chance of human error during
testing.
3. Tests execution can be scheduled for a nightly run using CI tools like
Jenkins which can also be configured to provide daily test results to
relevant stakeholders.
4. Automation testing is very less resource-intensive. Once the tests are
automated, test execution requires almost no time of QAs. Saving QA
bandwidth for other exploratory tasks.

Ques.13. What are some disadvantages of automation testing.

Ans. Some disadvantages of automation testing are-


1. It requires skilled automation testing experts to write test scripts.
2. Additional effort to write scripts is required upfront.
3. Automation scripts are limited to verification of the tests that are coded.
These tests may miss some error that is very glaring and easily identifiable
to human(manual QA).
4. Even with some minor change in the application, script update and
maintenance is required.

Ques.14. What is performance testing.

Ans. Performance testing is a type of non-functional testing in which the


performance of the system is evaluated under expected or higher load. The
various performance parameters evaluated during performance testing are –
response time, reliability, resource usage, scalability, etc. The different types of
performance testing are – Load, Stress, Endurance, Spike, and Volume Testing.
Ques.15. What is a test bed?
Ans. A test bed is a test environment used for testing an application. A test
bed configuration can consist of the hardware and software requirement of
the application under test including – operating system, hardware
configurations, software configurations, tomcat, database, etc.

Ques.16. What is a test plan?


Ans. A test plan is a formal document describing the scope of testing, the
approach to be used, resources required and time estimate of carrying out the
testing process. It is derived from the requirement documents (Software
Requirement Specifications).

Ques.17. What is a test scenario?


Ans. A test scenario is derived from a use case. It is used for end to end testing
of a feature of an application. A single test scenario can cater to multiple test
cases. The scenario testing is particularly useful when there is time constraint
while testing.

Ques.18. What is a Test case?


Ans. A test case is used to test the conformance of an application with its
requirement specifications. It is a set of conditions with pre-requisites, input
values and expected results in a documented form.

Ques.19. What are some attributes of a test case?


Ans. A test case can have the following attributes-
1. TestCaseId – A unique identifier of the test case.
2. Test Summary – One-liner summary of the test case.
3. Description – Detailed description of the test case.
4. Prerequisite or pre-condition – A set of prerequisites that must be
followed before executing the test steps.
5. Test Steps – Detailed steps for performing the test case.
6. Expected result – The expected result in order to pass the test.
7. Actual result – The actual result after executing the test steps.
8. Test Result – Pass/Fail status of the test execution.
9. Automation Status – Identifier of automation – whether the application
is automated or not.
10. Date – The test execution date.
11. Executed by – Name of the person executing the test case.
Ques.20. What is Test data?
Ans. Test data is data that is used to test the software with different inputs and
helps to check whether the corresponding output is as per the expected result
or not. This data is created based on the business requirements.

Ques.21. What is a Test script?


Ans. A test script is an automated test case written in any programming or
scripting language. These are basically a set of instructions to evaluate the
functioning of an application.

Ques.22. What is Error in Software Testing?


Ans Since we all are humans so it is obvious to make a mistake. Likewise, error
is a similar case that happens in software testing due to some missing scenario
in the requirements, some issues in design or some mistakes in the
implementation.

Ques.23. What is a Bug?


Ans. A bug is a fault in a software product detected at the time of testing,
causing it to function in an unanticipated manner.

Ques.24. What is a defect?


Ans. A defect is non-conformance with the requirement of the
product detected in production (after the product goes live).

Ques.25. What are some defect reporting attributes?


Ans. Some of the attributes of a Defect report are-
• DefectId – A unique identifier of the defect.
• Defect Summary – A one-line summary of the defect, more like a defect
title.
• Defect Description – A detailed description of the defect.
• Steps to reproduce – The steps to reproduce the defect.
• Expected Result – The expected behavior from which the application is
deviating because of the defect.
• Actual Result- The current erroneous state of the application w.r.t. the
defect.
• Defect Severity – Based on the criticality of the defect, this field can be
set to minor, medium, major or show stopper.
• Priority – Based on the urgency of the defect, this field can be set on a
scale of P0 to P3.

Ques.26. What are some of the bug or defect management tools?


Ans. Some of the most widely used Defect Management tools are – Jira,
Bugzilla, Redmine, Mantis, Quality Center, etc.

Ques.27. What is defect density?


Ans. Defect density is the measure of the density of the defects in the system.
It can be calculated by dividing the number of defects identified by the total
number of lines of code(or methods or classes) in the application or program.

Ques.28. What is defect priority?


Ans. A defect priority is the urgency of fixing the defect. Normally the defect
priority is set on a scale of P0 to P3 with P0 defect having the most urgency to
fix.

Ques.29. What is defect severity?


Ans. Defect severity is the severity of the defect impacting the functionality.
Based on the organization, we can have different levels of defect severity
ranging from minor to critical or show stopper.

Ques.30. Give an example of Low priority-Low severity, Low priority-High


severity, High priority-Low severity, High priority-High severity defects.
Ans. Below are the examples for different combinations of priority and
severity-
1. Low priority-Low severity – A spelling mistake in a page not frequently
navigated by users.
2. Low priority-High severity – Application crashing in some very corner
case.
3. High priority-Low severity – Slight change in logo color or spelling
mistake in the company name.
4. High priority-High severity – Issue with login functionality.

For details, check – Priority & Severity with Examples


Ques.31. What is a blocker?
Ans. A blocker is a bug of high priority and high severity. It prevents or blocks
testing of some other major portion of the application as well.

Ques.32. What is a critical bug?


Ans. A critical bug is a bug that impacts a major functionality of the
application and the application cannot be delivered without fixing the bug. It
is different from the blocker bug as it doesn’t affect or blocks the testing of
other parts of the application.

Ques.33. Explain the bug life cycle or the different states of a bug.
Ans. A bug goes through the following phases in software development-
• New – A bug or defect when detected is in New state.
• Assigned – The newly detected bug when assigned to the
corresponding developer is in the Assigned state.
• Open – When the developer works on the bug, the bug lies in the Open
state.
• Rejected/Not a bug – A bug lies in rejected state in case the developer
feels the bug is not genuine.
• Deferred – A deferred bug is one, fix of which is deferred for some
time(for the next releases) based on the urgency and criticality of the
bug.
• Fixed – When a bug is resolved by the developer it is marked as fixed.
• Test – When fixed the bug is assigned to the tester and during this time
the bug is marked as in Test.
• Reopened – If the tester is not satisfied with the issue resolution the bug
is moved to the Reopened state.
• Verified – After the Test phase, if the tester feels the bug is resolved, it is
marked as verified.
• Closed – After the bug is verified, it is moved to Closed status.

Ques.34. What are the different test design techniques.

Ans. Test design techniques are different standards of test designing that allow
systematic and widely accepted test cases. The different test design techniques
can be categorized as static test design techniques and dynamic test design
techniques.
1. Static Test Design Techniques – The test design techniques which involves
testing without executing the code. The various static test design
techniques can be further divided into two parts manual and using tools-

• Manual static design techniques


• Walkthrough
• Informal reviews
• Technical reviews
• Audit
• Inspection
• Management review
• Static design techniques using tools
• Static analysis of code – It includes analysis of the different paths
and flows in the application and different states of the test data.
• Compliance with coding standard – This evaluates the compliance
of the code with the different coding standards.
• Analysis of code metrics – The tool used for static analysis is
required to evaluate the different metrics like lines of code,
complexity, code coverage, etc.
2. Dynamic Test Design Techniques – Dynamic test design techniques
involve testing by running the system under test.
• Specification-based – Specification-based test design techniques are
also referred to as black-box testing. These involve testing based on
the specification of the system under test without knowing its internal
architecture.
• Structure-based – Structure-based test design techniques are also
referred to as white box testing. In these techniques, the knowledge of
code or internal architecture of the system is required to carry out the
testing.
• Experienced-based – The experienced-based techniques are
completely based on the experience or intuition of the tester. The two
most common forms of experienced-based testing are – Adhoc testing
and exploratory testing.

Ques.35. What is Static Testing.


Ans. Static testing is a kind of testing for reviewing the work products or
documentation that are being created throughout the entire project. It allows
reviewing the specifications, business requirements, documentation, processes
and functional requirements in the initial phase of testing.
So that the testers involved in it can understand the requirements in more detail
before starting the testing lifecycle which intends to help in delivering the
quality product.

Ques.36. What is Dynamic Testing.


Ans. Testing performed by executing or running the application under test
either manually or using automation.

Ques.37. Explain the different types of specification-based test design


techniques.

Ans. Specification-based test design techniques are also referred to as black-


box testing. It involves testing based on the specification of the system under
test without knowing its internal architecture. The different types of
specification-based test design or black box testing techniques are-
• Equivalence partitioning – Grouping test data into logical groups or
equivalence classes with the assumption that all the data items lying in
the classes will have the same effect on the application.

• Boundary value analysis – Testing using the boundary values of the


equivalence classes taken as the test input.

• Decision tables – Testing using decision tables showing the application’s


behavior based on a different combination of input values.

• Cause-effect graph – Testing using a graphical representation of the


result or outcome and all the factors that affect the outcome.

• State transition testing – Testing based on the state machine model.

• Use case testing – Testing carried out using use cases.

Ques.38. Explain equivalence class partitioning.


Ans. Equivalence class partitioning is a specification-based black-box testing
technique. In equivalence class partitioning, a set of input data that defines
different test conditions are partitioned into logically similar groups such that
using even a single test data from the group for testing can be considered as
similar to using all the other data in that group.

For example, for testing a Square program (a program that prints the square
of a number), the equivalence classes can be-
Set of Negative numbers, whole numbers, decimal numbers, set of large
numbers, etc.

Ques.39. What is boundary value analysis.

Ans. Boundary value analysis is a software testing technique for designing test
cases wherein the boundary values of the classes of the equivalence class
partitioning are taken as input to the test cases e.g. if the test data lies in the
range of 0-100, the boundary value analysis will include test data – 0,1, 99, 100.

Ques.40. What is decision table testing.

Ans. Decision table testing is a type of specification-based test design technique


or black-box testing technique in which testing is carried out using decision
tables showing the application’s behaviour based on different combinations of
input values.

Decision tables are particularly helpful in designing test cases for complex
business scenarios involving verification of application with multiple
combinations of input.

Ques.41. What is a cause-effect graph.

Ans. A cause-effect graph testing is a black-box test design technique in which


graphical representation of input i.e. cause and output i.e. effect is used for test
designing. This technique uses different notations representing AND, OR, NOT,
etc relations between the input conditions leading to output.

Ques.42. What is state transition testing.


Ans. State transition testing is a black box test design technique based on a
state machine model. State transition testing is based on the concept that a
system can be defined as a collection of multiple states and the transition from
one state to another happens because of some event.

Ques.43. What is the use case testing.

Ans. A use case testing is a black-box testing approach in which testing is carried
out using use cases. A use case scenario is seen as an interaction between the
application and actors(users). These use cases are used for depicting
requirements and hence can also serve as a basis for acceptance testing.

Ques.44. What is Test Coverage.

Ans. It is a metric that measures the amount of testing performed on software


while executing the test cases. Test coverage for any software can be calculated
as the percentage of the number of test areas or coverage items covered with
respect to the total number of test areas.

The higher the test coverage, the more the part of the software gets covered by
test cases and hence, the more effective will be the testing.

Ques.45. What is structure-based testing.

Ans. Structure-based test design techniques are also referred to as white box
testing. In these techniques, the knowledge of code or internal architecture of
the system is required to carry out the testing. The various kinds of testing
structure-based or white testing techniques are-
• Statement testing – A white box testing technique in which the test
scripts are designed to execute the application’s code statements. Its
coverage is measured as the line of code or statements executed by test
scripts.

• Decision testing/branch testing – A testing technique in the test scripts


is designed to execute the different decision-branches (e.g. if-else
conditions) in the application. Its coverage is measured as the percentage
of decision points out of the total decision points in the application.
• Condition testing – Condition testing is a testing approach in which we
test the application with both True and False outcome for each condition.
Hence for n conditions, we will have 2n test scripts.

• Multiple condition testing – In multiple condition testing, the different


combinations of condition outcomes are tested at least once. Hence for
100% coverage, we will have 2^n test scripts. This is very exhaustive and
very difficult to achieve 100% coverage.

• Condition determination testing – It is an optimized way of multiple


condition testing in which the combinations which don’t affect the
outcomes are discarded.

• Path testing – Testing the independent paths in the system(paths are


executable statements from entry to exit points).

Ques.46. What is code coverage.


Ans. Code coverage is the measure of the amount of code covered by the test
scripts. It gives the idea of the part of the application covered by the test suite.

Ques.47. What are Statement testing and statement coverage in white


box testing.
Ans. Statement testing is a white box testing approach in which test scripts are
designed to execute code statements.

Statement coverage is the measure of the percentage of statements of code


executed by the test scripts out of the total code statements in the application.
The statement coverage is the least preferred metric for checking test
coverage.

Ques.48. What is decision testing or branch testing.

Ans. Decision testing or branch testing is a white box testing approach in which
test coverage is measured by the percentage of decision points(e.g. if-else
conditions) executed out of the total decision points in the application.
Also, check – Top SQL Queries Asked in Interviews

Ques.49. What are the different levels of testing?


Ans. Testing can be performed at different levels during the development
process. Performing testing activities at multiple levels helps in the early
identification of bugs. The different levels of testing are –
1. Unit Testing
2. Integration Testing
3. System Testing
4. Acceptance Testing

Ques.50. What is unit testing.


Ans. Unit testing is the first level of testing and it involves testing individual
modules of the software. It is usually performed by developers.

Ques.51. What is integration testing.


Ans. Integration testing is performed after unit testing. In integration testing,
we test the group of related modules. It aims at finding interfacing issues
between the modules.

Ques.52. What are the different types of integration testing.


Ans. The different type of integration testing is-
1. Big bang Integration Testing – In big bang integration testing, testing
starts only after all the modules are integrated.

2. Top-down Integration Testing – In top-down integration,


testing/integration starts from top modules to lower-level modules.

3. Bottom-up Integration Testing – In bottom-up integration, testing starts


from lower-level modules to higher-level modules up in the hierarchy.

4. Hybrid Integration Testing – Hybrid integration testing is the


combination of both Top-down and bottom-up integration testing. In
this approach, the integration starts from the middle layer and testing is
carried out in both the direction
For details check Integration testing.

Ques.53. What is a stub.


Ans. In the case of top-down integration testing, many times lower-level
modules are not developed while beginning testing/integration with top-level
modules. In those cases, Stubs or dummy modules are used that simulate the
working of modules by providing a hard-coded or expected output based on
the input values.

Ques.54. What is a driver.


Ans. In the case of bottom-up integration testing, drivers are used to
simulating the working of top-level modules in order to test the related
modules lower in the hierarchy.

Ques.55. What is system testing.


Ans. System testing is the level of testing where the complete software is
tested as a whole. The conformance of the application with its business
requirements is checked in system testing.

Ques.56. What is acceptance testing.


Ans. Acceptance testing is testing performed by the potential end-user or
customers to check if the software conforms to the business requirements and
can be accepted for use.

Ques.57. What is UAT Testing.


Ans UAT testing is the last phase of the testing lifecycle. Its main focus is to
validate that software is working in accordance with business requirements. It
also ensures that the application is user-friendly and can handle complex
scenarios at its best before releasing the product to real-world users.

Ques.58. What is End-To-End Testing.


Ans. End-to-End testing is a type of testing where the entire application
undergoes testing, to test each functionality of the software is working as
expected and there is no loophole remaining in it. It ensures that the
application is user-friendly and meets the business requirements.

Ques.59. What is alpha testing.


Ans. Alpha testing is a type of acceptance testing that is performed testers or
the internal employees of the organization at the developer site.

Ques.60. What is beta testing.


Ans. Beta testing is the testing done by end-users at the end user’s site. It
allows users to provide direct input about the software to the development
company.
Ques.61. What is Adhoc Testing.
Ans. Adhoc testing is an unstructured way of testing that is performed without
any formal documentation or proper planning.

Ques.62. What is monkey testing.


Ans. Monkey testing is a type of testing that is performed randomly without
any predefined test cases or test inputs.

Ques.63. How is monkey testing different from Adhoc testing.


Ans. In the case of Adhoc testing although there are no predefined or
documented test cases still testers have an understanding of the application.
While in the case of monkey testing testers don’t have any understanding of
the application.

Ques.64. What is exploratory testing.


Ans. Exploratory testing is a type of testing in which new test cases are added
and updated while exploring the system or executing test cases. Unlike
scripted testing, test design and execution go parallelly in exploratory testing.

Ques.65. What is load testing.


Ans. Load testing is a type of performance testing which aims at finding an
application’s performance under the expected workload. During load testing,
we evaluate the response time, throughput, error rate, etc parameters of the
application.

Ques.66. What is stress testing.


Ans. Stress testing is a type of performance testing in which an application’s
behavior is monitored under a higher workload than expected. Stress testing is
done to find memory leaks and the robustness of the application.

Ques.67. What is volume testing.


Ans. Volume testing is a type of performance testing in which the performance
of the application is evaluated with a large amount of data. It checks the
scalability of the application and helps in the identification of a bottleneck
with a high volume of data.

Ques.68. What is endurance testing or Soak testing.


Ans. Endurance testing is a type of performance testing which aims at finding
issues like memory leaks when an application is subjected to load test for a
long period of time.

Ques.69. What is spike testing.


Ans. Spike testing is a type of performance testing in which the application’s
performance is measured while suddenly increasing the number of active
users during the load test.

Ques.70. What is UI testing.


Ans. UI or user interface testing is a type of testing that aims at finding
Graphical User Interface defects in the application and checks that the GUI
conforms to the specifications.

Ques.71. What is usability testing.


Ans. Usability testing is the type of testing that aims at determining the ease
of using the application. It aims at uncovering the usability defects in the
application.

Ques.72. What is Accessibility testing.


Ans. Accessibility testing is the type of testing which aims at determining the
ease of use or operation of the application specifically for people with
disabilities.

Ques.73. What is compatibility testing.


Ans. Compatibility testing is validating software to see how compatible the
software is with a particular environment – operating system, platform, or
hardware.

Ques.74. What is configuration testing.


Ans. Configuration testing is the type of testing used to evaluate the
configurational requirements of the software along with the effect of changing
the required configuration.

Ques.75. What is localization testing.


Ans. Localization testing is a type of testing in which we evaluate the
application’s customization(a localized version of the application) in a
particular culture, locale or country.
Ques.76. What is globalization testing.
Ans. Globalization testing is a type of testing in which application is evaluated
for its functioning across the world in different cultures, languages, locales,
and countries.

Ques.77. What is negative testing.


Ans. Negative testing is a type of testing in which the application’s
robustness(graceful exiting or error reporting) is evaluated when provided
with invalid input or test data.

Ques.78. What is security testing.


Ans. Security testing is a type of testing which aims at evaluating the integrity,
authentication, authorization, availability, confidentiality, and non-repudiation
of the application under test.

Ques.79. What is penetration testing.


Ans. Penetration testing or pen testing is a type of security testing in which
application is evaluated(safely exploited) for different kinds of vulnerabilities
that any hacker could exploit.

Ques.80. What is robustness testing.


Ans. Robustness testing is a type of testing that is performed to find the
robustness of the application i.e. the ability of the system to behave gracefully
in case of erroneous test steps and test input.

Ques.81. What is concurrency testing.


Ans. Concurrency testing is a multi-user testing in which an application is
evaluated by analyzing the application’s behavior with concurrent users
accessing the same functionality.

Ques.82. What is backend testing.


Ans. Backend testing is a type of testing that involves testing the backend of
the system which comprises testing the databases and the APIs in the
application.

Ques.83. What is A/B testing.


Ans. A/B testing is a type of testing in which the two variants of the software
product are exposed to the end-users and on analyzing the user behavior on
each variant, the better variant is chosen and used thereafter.
Ques.84. What is risk analysis.
Ans. Risk analysis is the analysis of the risk identified and assigning an
appropriate risk level to the defect based on its impact over the application.

Ques.85. What is the difference between regression and retesting.


Ans. Regression testing involves testing the application to verify that a new
code change doesn’t affect the other parts of the application. Whereas, in
retesting, we verify if the fixed issue is resolved or not.

Ques.86. What is the difference between black-box and white-box


testing.
Ans. Black-box testing is a type of testing in which the internal architecture of
the code is not required for testing. It is usually applicable for system and
acceptance testing.

Whereas white-box testing requires internal design and implementation


knowledge of the application being tested. It is usually applicable for Unit and
Integration testing.

Ques.87. What is the difference between smoke and sanity testing.


Ans. The difference between smoke and sanity testing is-
• Smoke testing is a type of testing in which all major functionalities of
the application are tested before carrying out exhaustive testing.
Whereas, sanity testing is a subset of regression testing which is carried
out when there is some minor fix in the application in a new build.
• In smoke testing, shallow-wide testing is carried out while in Sanity,
narrow-deep testing (for a particular functionality) is done.
• The smoke tests are usually documented or are automated. Whereas,
the sanity tests are generally not documented or unscripted.

Ques.88. What is the difference between Release and Build.


Ans. A build is an executable file provided by the developers to the testing
team for testing the application. It undergoes various iterations of fixing and
testing until the application works as expected. Once the application becomes
stable and ready for the end-users, it’s released in the market.

Whereas, a release is an installable software provided to the end-users after it


gets certified by the testing team. During the release of any software to the
client, release notes are attached to it that includes a number of defects still
open, covered user stories, change-requirements, and version of the release.

Manual Testing Interview Questions for


Experienced
Ques.89. What is the difference between bug leakage and bug release.
Ans. Bug leakage is when the tested software is released into the market and
the end-user finds bugs in it. These include the bugs that got missed by the
testing team during the testing phase.

Whereas, bug release is when a specific version of the software is released in


the market with some known bugs which are intended to get fixed in the later
versions. These types of issues are of low priority and are mentioned in the
release notes while sharing with the end-users.

Ques.90. What do you mean by Defect Triage.


Ans. Defect triage is a process in which the defects are prioritized based on
different factors like severity, risk, the time required to fix the bug, etc. The
defect triage meeting includes the different stakeholders – the development
team, testing team, project manager, BAs, etc, which decide the priority of
fixing the defects.

Ques.91. What is a test harness? Why do we need a test harness.


Ans. A test harness is a collection of test scripts and test data usually
associated with the unit and integration testing. It involves stubs and drivers
that are required for testing software modules and integrated components.

Ques.92. What is all pair testing.


Ans. All pair testing is a type of testing in which the application is tested with
all possible combinations of the values of input parameters.

Ques.93. What is failover testing.


Ans. Failover testing is a type of testing that is used to verify the application’s
ability to allocate more resources(more servers) in case of failure and
transferring the processing part to the back-up system.

Ques.94. What is fuzz testing.


Ans. Fuzz testing is a type of testing in which a large amount of random data
is provided as input to the application in order to find security loopholes and
other issues in the application.

Ques.95. What is pilot testing.


Ans. Pilot testing is testing carried out as a trial by a limited number of users
to evaluate the system and provide their feedback before the complete
deployment is carried out.

Ques.96. What is dev-box Testing.


Ans. In dev-box testing, a tester performs testing on the developer’s system to
verify if the major functionalities of the application are stable and ready for
testing.

Ques.97. What is mutation testing.


Ans. Mutation testing is a type of white box testing in which the source code
of the application is mutated to cause some defects in its working. After that,
the test scripts are executed to check for their correctness by verifying the
failures caused by the mutant code.

Ques.98. What is the requirement traceability matrix(RTM).


Ans. In software testing, a requirement traceability matrix is a table that relates
the high-level requirements with either detailed requirements, test plans, or
test cases. RTM helps in ensuring 100% test coverage.

Ques.99. What is cyclomatic complexity.


Ans. Cyclomatic complexity is the measure of the number of independent
paths in an application or program. This metric provides an indication of the
amount of effort required to test complete functionality. It can be defined by
the expression –
L – N + 2P, where:
L is the number of edges in the graph
N is the number of nodes
P is the number of disconnected parts
Ques.100. What are the entry criteria in software testing.
Ans. A set of prerequisites that are required to kick-off the testing activity and
that includes Test environment, Test tool, Test Data, database connectivity,
and many more.

Ques.101. What is exit criteria in software testing.


Ans. An exit criteria is a formal set of conditions that specify the agreed-upon
features or state of the application in order to mark the completion of the
process or product.

Ques.102. What is the difference between testing and debugging.

Ans. Testing is primarily performed by the testing team in order to find the
defects in the system. Whereas, debugging is an activity performed by the
development team. In debugging the cause of the defect is located and fixed.
Thus removing the defect and preventing any future occurrence of the defect
as well.

Another difference between the two is – testing can be done without any
internal knowledge of software architecture. Whereas debugging requires
knowledge of software architecture and coding.

Ques.103. Explain the Agile methodology.


Ans. The agile methodology of software development is based on an iterative
and incremental approach. In this model, the application is broken down into
smaller builds on which different cross-functional teamwork together
providing rapid delivery along with adapting to changing needs at the same
time.
Also, check – Agile vs Waterfall | Selecting the right model for your project

Ques.104. What is scrum.


Ans. A scrum is a process for implementing Agile methodology. In scrum, time
is divided into sprints and on completion of sprints, a deliverable is shipped.

Ques.105. What are the different roles in scrum.


Ans. The different roles in scrum are –
1. Product Owner – The product owner owns the whole development of
the product, assigns tasks to the team and acts as an interface between
the scrum team(development team) and the stakeholders.
2. Scrum Master – The scrum master monitors that scrum rules get
followed in the team and conducts scrum meetings.
3. Scrum Team – A scrum team participate in the scrum meetings and
perform the tasks assigned.

Ques.106. What is a scrum meeting.


Ans. A scrum meeting is a daily meeting in the scrum process. This meeting is
conducted by scrum master and update of the previous day’s work along with
the next day’s task and context is defined in this meeting.

Ques.107. Explain TDD (Test Driven Development).


Ans. Test-Driven Development is a software development methodology in
which the development of the software is driven by test cases created for the
functionality to be implemented. In TDD, first, the test cases are created and
then code to pass the tests is written. Later the code is refactored as per the
standards.

Ques.108. What is the difference between Latent and Masked Defects.


Ans. A latent defect is an unidentified defect present in the current release but
is not visible because the conditions in which the defect could be found have
never met. These types of defects occur only when a particular event gets
triggered which was concealing their presence.

Whereas a masked defect is an existing defect that has not yet caused any
failure because another error has masked it or prevented it from getting
discovered.

Ques.109. What is the PDCA cycle in software testing.


Ans. PDCA cycle is a key for continuous process improvement in software
development. It includes the following 4 steps-
• Plan – Plan the objectives, goals, initiatives which help to reach customer
satisfaction.
• Do – It implements the plan into action. To serve the customer with
better quality and satisfaction it is necessary to have a good plan to
execute.

• Check – To check the progress of your plan which has been


implemented. The result will show how accurate the planning had been
done.

• Act – Acting upon the results to do further improvement which helps in


achieving the planned goals.

Ques.110. What is Defect Cascading.


And. Defect cascading is the triggering of a defect by another defect. It
happens when a defect is not caught by the testing team and it gives rise to
another defect.

Ques.111. What is a test metric.

Ans. Test Metric is a quantitative analysis that helps in monitoring the progress
of a software project. Every project has its own timeline so to ensure the delivery
of the project on time requires setting deliverables at different intervals and this
aspect of measuring the progress is provided by test metrics.

Ques.112. What is Context-driven testing.

Ans. Context-driven testing is the type of testing that involves adopting the
test practices, methodologies and at times customizing them based on the
context of the project.
In this type of testing, instead of following best practices, we follow what
works best for the project based on the skills, experience, and judgment of the
testing team. For details check – Context-driven methodology by James Bach
Table of Contents

What is API? 4

What is API Testing? 6

What is REST API? 6

Difference between REST API vs SOAP API. 8

What to Test in API Testing? 8

HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10

HTTP Methods explained. 12


HTTP GET Method Explained - 12
HTTP POST Method Explained - 13
HTTP PUT Method Explained - 13
HTTP PATCH Method Explained - 14
HTTP DELETE & OPTIONS Method Explained - 14
HTTP HEAD/TRACE Method Explained - 15

How to Test an API ( API Testing)? 15

API Testing tools 16

How to do API Testing using Postman 16


What is API?

API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.

For example, It like a connector as seen in the picture. All data connects to our organization through API.

In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.

API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API

Type of APIs :-
What is API Testing?

When we talk about API Testing,

API testing is testing that APIs and its integration with the services.

It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..

In this definite guide,


We are basically discussing about the REST API Testing.Where we need to test the REST APIs for the
validation, error codes and load testing.

What is REST API?


As REST is an acronym for REpresentational State Transfer, statelessness is key. An API can be REST if it
follows the below constraints.

The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.

1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand

Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,

First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.

Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..

Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.

Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.

Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.

Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.

If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).

SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.

Enough of background lets come to topic…

What to Test in API Testing?

● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.

Lets understand why API Testing is important…


Why you should perform API Testing?
● Many of the services that we use every day rely on hundreds of different interconnected APIs, if any
one of them fails then the service will not work.

● Right now, Internet uses millions of APIs and they should be tested thoroughly.

● Developers make mistake and they create buggy APIs..

● Validation of APIs is very important which are going live to production.

Above image shows the architecture of an application and notice that API Testing is important part..

Now…

Lets learn one more concept HTTP Methods

HTTP - Fundamentals

HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.

HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.

What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.

GET /spec.html HTTP/1.1


Host: www.example.org
Cookie: theme=light; sessionToken=abc123

Record the user's browsing activity.


Which pages were visited in the past.
Contain the name of the domain & Lifetime.

Tool : EditThisCookie - http://bit.ly/1oe1o08

What is Authentication and its types lets understand it...

What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.

Basic authentication - String is encoded with Base64.


curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com
Digest Authentication - Authentication is performed by transmitting the password in an ENCRYPTED
form.(With Some Salt etc)

OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.

E.g OAuth 1, 2.

More authentication are discussed here -


https://scrolltest.com/2018/11/22/how-to-handle-authentications-with-postman/

In Client as Browser and Server as DB with the service running in PHP.

We can create an HTTP request from browser by typing a URL.

Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL

Lets Understand what all HTTP methods are present


HTTP Methods explained.

HTTP GET Method Explained -

.
HTTP POST Method Explained -

HTTP PUT Method Explained -


HTTP PATCH Method Explained -

HTTP DELETE & OPTIONS Method Explained -


HTTP HEAD/TRACE Method Explained -

Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.

How to Test an API ( API Testing)?

Before that take a look into the example api that can available freely.

https://api.chucknorris.io/jokes/random

Here Keys are


cateroy, icon_url, id, url and value and they have corresponding values as String or number.
API Testing can be done manually or using a Tools. It is always recommend to certain tools.

Lets learn API Testing using our favorite tools..


Below is the list of API testing tools, You can learn or use whichever tool you feel is great for you, I encourage
you to start with Postman it's an awesome API Testing tool which provide lots of feature like command line,
CI/CD and monitoring of APIs with testcase support.

API Testing tools

● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD

API Testing using POSTMAN


What is Postman?

First of all, let’s understand what is Postman.

It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.

You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.

Its available in the MacOS, Windows and Linux as Native app.

Download Postman - https://www.getpostman.com


Major features of postman
Top API Testing Tools
Katalon Postman
SoapUI Rest-Assured
CITRUS Karate
Jmeter apigee
API Terminologies
API Application Programming Interface (API) is software that acts as an intermediary for
two apps to communicate with each other.
HTTP Hypertext Transfer Protocol is the collection of rules for the transmission of data on
the World Wide Web, like graphic images, text, video, sound, and other multimedia
HTTPS The S in HTTPS stands for "secure." HTTPS uses TLS (or SSL) to encrypt HTTP requests
and responses
URI Uniform Resource Identifier is a string identifier that refers to a resource on the
internet. It is a string of characters that is used to identify any resource on the
internet using location, name, or both.
URL Uniform Resource Locator is used to find the location of the resource on the web. It is
a reference for a resource and a way to access that resource. A URL always shows a
unique resource, and it can be an HTML page, a CSS document, an image, etc.
Layers of API Testing
Three separate layers Presentation (or user interface) layer, the business layer, and the database layer for
modeling and manipulating data.
API Test Actions
Verify correct HTTP status For example, creating a resource should return 201 CREATED and unpermitted
code requests should return 403 FORBIDDEN, etc.
Verify response payload Check valid JSON body and correct field names, types, and values — including in error
responses.
Verify response headers HTTP server headers have implications on both security and performance.
Verify correct application This is optional and applies mainly to manual testing, or when a UI or another
state interface can be easily inspected.
Verify basic performance In case an operation was completed successfully but took an unreasonable amount of
sanity time, the test fails.
API Test Scenario Categories
1 Basic positive tests (happy paths)
2 Extended positive testing with optional parameters
3 Destructive testing
4 Security, authorization, and permission tests (which are out of the scope of this post)
5 Negative testing with valid input
6 Negative testing with invalid input
API Example with Test Matrix
API Call Action
GET /users List all users
GET Get user by username
/users?name={username}
GET /users/{id} Get user by ID
GET Get all configurations for user
/users/{id}/configurations
POST Create a new configuration for user
/users/{id}/configurations
DELETE Delete configuration for user
/users/{id}/configurations/{i
d}
PATCH Update configuration for use
/users/{id}/configuration/{id}

Web Services
SOAP (Simple Object Access Protocol) is a standard protocol defined by the W3C standards
for sending and receiving web service requests and responses.
REST (REpresentational State Transfer) is the web standards-based architecture that uses
HTTP. Unlike SOAP-based Web services, there is no official standard for RESTful Web
CRUD Create, Read, Update & Delete
HTTP Request Methods
GET It fetches the information from the server. Moreover, it is the most commonly used
method which does not have a request body. Every time you open a website, the Get
request fires to retrieve the website contents. Additionally, it is equivalent to the
POST It works to send data to the server. User may add or update data using the Post
request. They send the information that needs to update in the request body.
PUT It is similar to the Post method since it updates the data. The only difference is that
we use it when we have to replace an existing entity completely
PATCH It s again similar to Post and Put methods, but user use it when they have to update
some data partially. Moreover, unlike the Post and Put methods, user may send only
the entity that needs updation in the request body with the Patch method.
HEAD It is similar to the Get method, but it retrieves only the header data and not the
entire response body. User use it when they need to check the document's file size
without downloading the document.
DELETE It deletes the server's representations of resources through the specific URL.
Additionally, just like the Get method, it does not have a request body.
OPTIONS It is not a widely used method when compared to other ones. It returns data
specifying the different methods and the operations supported by the server at the
HTTP Response Status Codes
Code Description
1xx informational response, request was received, continuing process
100 Continue: The client can continue with the request as long as it doesn't get rejected.
101 Switching Protocols: The server is switching protocols.
102 Processing, It indicates that the server has received and is processing the request, but
no response is available yet.
103 Early Hints, it primarily intended to be used with the Link header, letting the user
agent start preloading resources while the server prepares a response.
2xx Success, request was successfully received, understood, and accepted
200 OK: The request succeeded
201 Created: The request succeeded, and a new resource was created as a result. This is
typically the response sent after POST requests, or some PUT requests.
202 Accepted: Request accepted for processing, but in progress
203 Non-Authoritative Information: The information in the entity header is not from an
original source but a third-party
204 No Content: Response with status code and header but no response body
205 Reset Content: The form for the transaction should clear for additional input
206 Partial Content: Response with partial data as specified in Range header
207 Multi-Status, Conveys information about multiple resources, for situations where
multiple status codes might be appropriate.
3xx Redirection, further action needed in order to complete the request
300 Multiple Choices: Response with a list for the user to select and go to a location
301 Moved Permanently: Requested page moved to a new url
302 Found: Requested page moved to a temporary new URL
303 See Other: One can find the Requested page under a different URL
305 Use Proxy: Requested URL need to access through the proxy mentioned in the
Location header
307 Temporary Redirect: Requested page moved to a temporary new URL
308 Permanent Redirect: This means that the resource is now permanently located at
another URI, specified by the Location: HTTP Response header.
4xx Client Error, request contains bad syntax or cannot be fulfilled
400 Bad Request: Server unable to understand the request
401 Unauthorized: Requested content needs authentication credentials
403 Forbidden: Access is forbidden
404 Not Found: Server is unable to find the requested page
405 Method Not Allowed: Method in the request is not allowed
407 Proxy Authentication Required: Need to authenticate with a proxy server
408 Request Timeout: The request took a long time as expected by the server
409 Conflict: Error in completing request due to a conflict
411 Length Required: We require the "Content-Length" for the request to process
415 Unsupported Media Type: Unsupported media-type
417 Expectation Failed, it means the expectation indicated by the Expect request header
field cannot be met by the server.
421 Misdirected Request, request was directed at a server that is not able to produce a
423 response.
Locked, the resource that is being accessed is locked
429 Too Many Requests,user has sent too many requests in a given amount of time
5xx Server Error, the server failed to fulfil an apparently valid request
500 Internal Server Error: Request not completed due to server error
501 Not Implemented: Server doesn't support the functionality
502 Bad Gateway: Invalid response from an upstream server to the server. Hence, the
request not complete
503 Service Unavailable: The server is temporarily down
504 Gateway Timeout: The gateway has timed out
505 HTTP Version Not Supported: Unsupported HTTP protocol version
507 Insufficient Storage, method could not be performed on the resource because the
server is unable to store the representation needed to successfully complete the
511 Network Authentication Required, it indicates that the client needs to authenticate
to gain network access
Cheat Sheet for API Testing with Postman
Author Haradhan Pal
YouTube https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Top API Testing Tools
Katalon Studio Postman
SoapUI Rest-Assured
CITRUS Karate
ReadyAPI Airborne
Jmeter apigee
API Terminologies
API Application Programming Interface (API) is software that acts as an intermediary for
two apps to communicate with each other.
HTTP Hypertext Transfer Protocol is the collection of rules for the transmission of data on
the World Wide Web, like graphic images, text, video, sound, and other multimedia
HTTPS The S in HTTPS stands for "secure." HTTPS uses TLS (or SSL) to encrypt HTTP requests
and responses
URI Uniform Resource Identifier is a string identifier that refers to a resource on the
internet. It is a string of characters that is used to identify any resource on the internet
using location, name, or both.
URL Uniform Resource Locator is used to find the location of the resource on the web. It is
a reference for a resource and a way to access that resource. A URL always shows a
unique resource, and it can be an HTML page, a CSS document, an image, etc.
Layers of API Testing
Three separate layers Presentation (or user interface) layer, the business layer, and the database layer for
modeling and manipulating data.
HTTP Important Response Status Codes
Code Description
1xx informational response, request was received, continuing process
100 Continue: The client can continue with the request as long as it doesn't get rejected.

101 Switching Protocols: The server is switching protocols.


102 Processing, It indicates that the server has received and is processing the request, but
no response is available yet.
103 Early Hints, it primarily intended to be used with the Link header, letting the user
agent start preloading resources while the server prepares a response.
2xx Success, request was successfully received, understood, and accepted
200 OK: The request succeeded
201 Created: The request succeeded, and a new resource was created as a result. This is
typically the response sent after POST requests, or some PUT requests.
202 Accepted: Request accepted for processing, but in progress
203 Non-Authoritative Information: The information in the entity header is not from an
original source but a third-party
204 No Content: Response with status code and header but no response body
205 Reset Content: The form for the transaction should clear for additional input
206 Partial Content: Response with partial data as specified in Range header
207 Multi-Status, Conveys information about multiple resources, for situations where
multiple status codes might be appropriate.
3xx Redirection, further action needed in order to complete the request
300 Multiple Choices: Response with a list for the user to select and go to a location
301 Moved Permanently: Requested page moved to a new url
302 Found: Requested page moved to a temporary new URL
303 See Other: One can find the Requested page under a different URL
305 Use Proxy: Requested URL need to access through the proxy mentioned in the
Location header
307 Temporary Redirect: Requested page moved to a temporary new URL
308 Permanent Redirect: This means that the resource is now permanently located at
another URI, specified by the Location: HTTP Response header.
4xx Client Error, request contains bad syntax or cannot be fulfilled
400 Bad Request: Server unable to understand the request
401 Unauthorized: Requested content needs authentication credentials
403 Forbidden: Access is forbidden
404 Not Found: Server is unable to find the requested page
405 Method Not Allowed: Method in the request is not allowed
407 Proxy Authentication Required: Need to authenticate with a proxy server
408 Request Timeout: The request took a long time as expected by the server
409 Conflict: Error in completing request due to a conflict
411 Length Required: We require the "Content-Length" for the request to process
415 Unsupported Media Type: Unsupported media-type
417 Expectation Failed, it means the expectation indicated by the Expect request header
field cannot be met by the server.
421 Misdirected Request, request was directed at a server that is not able to produce a
response.
423 Locked, the resource that is being accessed is locked
429 Too Many Requests,user has sent too many requests in a given amount of time
5xx Server Error, the server failed to fulfil an apparently valid request
500 Internal Server Error: Request not completed due to server error
501 Not Implemented: Server doesn't support the functionality
502 Bad Gateway: Invalid response from an upstream server to the server. Hence, the
request not complete
503 Service Unavailable: The server is temporarily down
504 Gateway Timeout: The gateway has timed out
505 HTTP Version Not Supported: Unsupported HTTP protocol version
507 Insufficient Storage, method could not be performed on the resource because the
server is unable to store the representation needed to successfully complete the
request
511 Network Authentication Required, it indicates that the client needs to authenticate to
gain network access
API Test Actions
Verify correct HTTP status For example, creating a resource should return 201 CREATED and unpermitted
code requests should return 403 FORBIDDEN, etc.
Verify response payload Check valid JSON body and correct field names, types, and values — including in error
responses.
Verify response headers HTTP server headers have implications on both security and performance.
Verify correct application This is optional and applies mainly to manual testing, or when a UI or another
state interface can be easily inspected.
Verify basic performance In case an operation was completed successfully but took an unreasonable amount of
sanity time, the test fails.
Client, Server and Host
Client A client is a computer hardware device or software that accesses a service made
available by a server. The server is often (but not always) located on a separate
physical computer.
Server A server is a physical computer dedicated to run services to serve the needs of other
computers. Depending on the service that is running, it could be a file server, database
server, home media server, print server, or web server.
Host A host is a computer, connected to other computers for which it provides data or
services over a network. In theory, every computer connected to a network acts as a
host to other peers on the network. In essence, a host reflects the logical relationship
of two or more computers on a network.
Types of API
Private APIs APIs builts solely for use within an organization, classified as an in-house application
for employees to automate business processes and delivery.
Public/Partner APIs Openly promoted but available for known developers or business partners, usually
represent software integrations between organizations.
External APIs Completely external APIs, as the name implies, which are available to any third-party
developer and are mostly designed or built for end-users/customers.
Author Haradhan Pal
YouTube https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
API Test Scenario Categories
1 Basic positive tests (happy paths)
2 Extended positive testing with optional parameters
3 Destructive testing
4 Security, authorization, and permission tests (which are out of the scope of this post)

5 Negative testing with valid input


6 Negative testing with invalid input
API Example with Test Matrix
API Call Action
GET /users List all users
GET Get user by username
/users?name={username}
GET /users/{id} Get user by ID
GET Get all configurations for user
/users/{id}/configurations
POST Create a new configuration for user
/users/{id}/configurations
DELETE Delete configuration for user
/users/{id}/configurations/{i
d}
PATCH Update configuration for use
/users/{id}/configuration/{id}

Web Services
SOAP (Simple Object Access Protocol) is a standard protocol defined by the W3C standards
for sending and receiving web service requests and responses.
REST (REpresentational State Transfer) is the web standards-based architecture that uses
HTTP. Unlike SOAP-based Web services, there is no official standard for RESTful Web
APIs.
CRUD Create, Read, Update & Delete
HTTP Request Methods
GET It fetches the information from the server. Moreover, it is the most commonly used
method which does not have a request body. Every time you open a website, the Get
request fires to retrieve the website contents. Additionally, it is equivalent to the read
operation.
POST It works to send data to the server. User may add or update data using the Post
request. They send the information that needs to update in the request body.
PUT It is similar to the Post method since it updates the data. The only difference is that we
use it when we have to replace an existing entity completely
PATCH It s again similar to Post and Put methods, but user use it when they have to update
some data partially. Moreover, unlike the Post and Put methods, user may send only
the entity that needs updation in the request body with the Patch method.

HEAD It is similar to the Get method, but it retrieves only the header data and not the entire
response body. User use it when they need to check the document's file size without
downloading the document.
DELETE It deletes the server's representations of resources through the specific URL.
Additionally, just like the Get method, it does not have a request body.
OPTIONS It is not a widely used method when compared to other ones. It returns data
specifying the different methods and the operations supported by the server at the
given URL.
Author Haradhan Pal
YouTube https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Checklist for Testing of
Web Application

Web Testing in simple terms is checking your web application for potential bugs be-
fore its made live or before code is moved into the production environment.

During this stage issues such as that of web application security, the functioning of
the site, its access to regular users and its ability to handle traffic is checked.

Types of Web App Testing

Functionality testing
What is Functional Testing ?
01. Testing the features and operational behavior of a product to ensure they corre-
spond to its specifications.
02. Testing that ignores the internal mechanism of a system or component and focus-
es solely on the outputs generated in response to selected inputs and execution
conditions.

Goal of Functional Testing :


The goal of Functional Testing is to verify whether your product meets the intended
functional specifications mentioned in your development documentation.

Testing Activities Included :


Test all the links in your webpages are working correctly and make sure there are
no broken links.
Links to be checked will include -
01. Outgoing links
02. Internal links
03. Anchor Links
04. MailTo Links
Test Forms are working as expected. This will include-
01. Scripting checks on the form are working as expected. For example- if a user
does not fill a mandatory field in a form an error message is shown.
02. Check default values are being populated.
03. Once submitted, the data in the forms is submitted to a live database or is
linked to a working email address.
04. Forms are optimally formatted for better readability.

Test Cookies are working as expected. Cookies are small files used by websites to
primarily remember active user sessions so you do not need to log in every time
you visit a website. Cookie Testing will include
01. Testing cookies (sessions) are deleted either when cache is cleared or when they
reach their expiry.
02. Delete cookies (sessions) and test that login credentials are asked for when you
next visit the site.

Test HTML and CSS to ensure that search engines can crawl your site easily. This
will include
01. Checking for Syntax Errors
02. Readable Color Schemas
03. Standard Compliance. Ensure standards such W3C, OASIS, IETF, ISO, ECMA, or
WS-I are followed.

Test business workflow- This will include


01. Testing your end - to - end workflow/ business scenarios which takes the user
through a series of web pages to complete.
02. Test negative scenarios as well, such that when a user executes an unexpected
step, appropriate error message or help is shown in your web application.

Functional Test Scenarios :


01. Test all the mandatory fields should be validated.
02. Test the asterisk sign should display for all the mandatory fields.
03. Test the system should not display the error message for optional fields.
04. Test that leap years are validated correctly & do not cause errors/miscalcula-
tions.
05. Test the numeric fields should not accept the alphabets and proper error
message should display.
06. Test for negative numbers if allowed for numeric fields.
07. Test division by zero should be handled properly for calculations.
08. Test the max length of every field to ensure the data is not truncated.
09. Test the pop up message (“This field is limited to 500 characters”) should dis-
play if the data reaches the maximum size of the field.
10. Test that a confirmation message should display for update and delete opera-
tions.
11. Test the amount values should display in currency format.
12. Test all input fields for special characters.
13. Test the timeout functionality.
14. Test the Sorting functionality. Test the Sorting functionality.
15. Test the functionality of the buttons available.
16. Test the Privacy Policy & FAQ is clearly defined and should be available for
users.
17. Test if any functionality fails the user gets redirected to the custom error
page.

usability testing
What is Usability Testing ?
01. Usability testing is nothing but the User-friendliness check.
02. In Usability testing, the application flow is tested so that a new user can un-
derstand the application easily.
03. Basically, system navigation is checked in Usability testing.

Goal of Usability Testing :


A Usability test establishes the ease of use and effectiveness of a product using a
standard Usability test practices.
Testing Activities Included :
Test the site Navigation:
01. Menus, buttons or Links to different pages on your site should be easily visible
and consistent on all webpages.
02. Test the Content.
03. Content should be legible with no spelling or grammatical errors.
04. Images if present should contain an “alt” text.

Usability Test Scenarios :


01. Web page content should be correct without any spelling or grammatical errors.
02. All fonts should be same as per the requirements.
03. All the text should be properly aligned.
04. All the error messages should be correct without any spelling or grammatical
errors and the error message should match with the field label.
05. Tool tip text should be there for every field.
06. All the fields should be properly aligned.
07. Enough space should be provided between field labels, columns, rows, and error
messages.
08. All the buttons should be in a standard format and size.
09. Home link should be there on every single page.
10. Disabled fields should be grayed out.
11. Check for broken links and images.
12. Confirmation message should be displayed for any kind of update and delete op-
eration.
13. Check the site on different resolutions (640 x 480, 600x800 etc.?)
14. Check the end user can run the system without frustration.
15. If there is an error message on submit, the information filled by the user should
be there.
16. Title should display on each web page
17. All fields (Textbox, dropdown, radio button etc) and buttons should be accessible
by keyboard shortcuts and the user should be able to perform all operations by
using keyboard.
18. Check if the dropdown data is not truncated due to the field size and also check
whether the data is hardcoded or managed via administrator.
interFace testing
Three areas to be tested here are - Application, Web and Database Server
01. Application: Test requests are sent correctly to the Database and output at the
client side is displayed correctly. Errors if any must be caught by the application
and must be only shown to the administrator and not the end user.
02. Web Server: Test Web server is handling all application requests without any
service denial.
03. Database Server: Make sure queries sent to the database give expected results.
Test system response when connection between the three layers (Application,
Web and Database) cannot be established and appropriate message is shown to the
end user.

Database testing

Database is one critical component of your web application and stress must be laid
to test it thoroughly. Testing activities will include-
01. Test if any errors are shown while executing queries.
02. Data Integrity is maintained while creating, updating or deleting data in data-
base.
03. Check response time of queries and fine tune them if necessary.
04. Test data retrieved from your database is shown accurately in your web appli-
cation.
To perform the Database testing, the tester should be aware of the below men-
tioned points:
01. The tester should understand the functional requirements, business logic, ap-
plication flow and database design thoroughly.
02. The tester should figure out the tables, triggers, store procedures, views and
cursors used for the application.
03. The tester should understand the logic of the triggers, store procedures, views
and cursors created.
04. The tester should figure out the tables which get affected when insert update
and delete (DML) operations are performed through the web or desktop appli-
cations.
Test Scenarios for Database Testing
01. Verify the database name: The database name should match with the specifica-
tions.
02. Verify the Tables, columns, column types and defaults. All things should match
with the specifications.
03. Verify whether the column allows a null or not.
04. Verify the Primary and foreign key of each table.
05. Verify the Stored Procedure.
06. Test whether the Stored procedure is installed or not.
07. Verify the Stored procedure name
08. Verify the parameter names, types and number of parameters.
09. Test the parameters if they are required or not.
10. Test the stored procedure by deleting some parameters
11. Test when the output is zero, the zero records should be affected.
12. Test the stored procedure by writing simple SQL queries.
13. Test whether the stored procedure returns the values
14. Test the stored procedure with sample input data.
15. Verify the behavior of each flag in the table.
16. Verify the data gets properly saved into the database after the each page submi-
sion.
17. Verify the data if the DML (Update, delete and insert) operations are performed.
18. Check the length of every field. The field length in the back end and front end
must be same.
19. Verify the database names of QA, UAT and production. The names should
beunique.
20. Verify the encrypted data in the database.
21. Verify the database size. Also test the response time of each query executed.
22. Verify the data displayed on the front end and make sure it is same in the back
end.
23. Verify the data validity by inserting the invalid data in the database.
24. Verify the Triggers.
compatibility testing

What is Compatibility Testing?


Compatibility testing is used to determine if your software is compatible with other
elements of a system with which it should operate, e.g. Browsers, Operating Sys-
tems, or hardware.

Goal of Compatibility Testing :


The purpose of Compatibility testing is to evaluate how well software performs in
a particular browser, Operating Systems, hardware or software. Compatibility tests
ensure that your web application displays correctly across different devices.

Testing Activities Included :


Browser Compatibility Test: Same website in different browsers will display dif-
ferently. You need to test if your web application is being displayed correctly across
browsers, JavaScript, AJAX and authentication is working fine. You may also check
for Mobile Browser Compatibility.

The rendering of web elements like buttons, text fields etc. changes with change
in Operating System. Make sure your website works fine for various combination
of Operating systems such as Windows, Linux, Mac and Browsers such as Firefox,
Internet Explorer, Safari etc.

Compatibility Test Scenarios :


01. Test the website in different browsers (IE, Firefox, Chrome, Safari and Opera)
and ensure the website is displaying properly.
02. Test the HTML version being used is compatible with appropriate browser
versions.
03. Test the images display correctly in different browsers.
04. Test the fonts are usable in different browsers.
05. Test the java script code is usable in different browsers.
06. Test the Animated GIF's across different browsers.
perFormance testing
What is Performance Testing ?
Performance Testing is conducted to evaluate the compliance of a system or
component with specified performance requirements.

Testing Activities Included :


01. Website application response times at different connection speeds.
02. Load test your web application to determine its behavior under normal and
peak loads.
03. Stress test your web site to determine its break point when pushed to be-
yond normal loads at peak time.
04. Test if a crash occurs due to peak load, how does the site recover from such
an event.
05. Make sure optimization techniques like gzip compression, browser and
server side cache enabled to reduce load times.

General Test Scenarios :


01. To determine the performance, stability and scalability of an application
under different load conditions.
02. To determine if the current architecture can support the application at
peak user levels.
03. To determine which configuration sizing provides the best performance
level.
04. To identify application and infrastructure bottlenecks.
05. To determine if the new version of the software adversely had an impact
on response time.
06. To evaluate product and/or hardware to determine if it can handle project-
ed load volumes.
security testing
Security Testing involves the test to identify any flaws and gaps from a security
point of view.

Test Scenarios for Security Testing :


01. Verify the web page which contains important data like password, credit card
numbers, secret answers for security question etc should be submitted via
HTTPS (SSL).
02. Verify the important information like password, credit card numbers etc should
display in encrypted format.
03. Verify password rules are implemented on all authentication pages like Regis-
tration, forgot password, change password.
04. Verify if the password is changed the user should not be able to login with the
old password.
05. Verify the error messages should not display any important information.
06. Verify if the user is logged out from the system or user session was expired, the
user should not be able to navigate the site.
07. Verify to access the secured and non secured web pages directly without login.
08. Verify the “View Source code” option is disabled and should not be visible to the
user.
09. Verify the user account gets locked out if the user is entering the wrong pass-
word several times.
10. Verify the cookies should not store passwords.
11. Verify if, any functionality is not working, the system should not display any ap-
plication, server, or database information. Instead, it should display the custom
error page.
12. Verify the SQL injection attacks.
13. Verify the user roles and their rights. For Example The requestor should not be
able to access the admin page.
14. Verify the important operations are written in log files, and that information
should be traceable.
15. Verify the session values are in an encrypted format in the address bar.
16. Verify the cookie information is stored in encrypted format.
17. Verify the application for Brute Force Attacks.
Checklist for Testing of
Web Application

Web Testing in simple terms is checking your web application for potential bugs be-
fore its made live or before code is moved into the production environment.

During this stage issues such as that of web application security, the functioning of
the site, its access to regular users and its ability to handle traffic is checked.

Types of Web App Testing

Functionality testing
What is Functional Testing ?
01. Testing the features and operational behavior of a product to ensure they corre-
spond to its specifications.
02. Testing that ignores the internal mechanism of a system or component and focus-
es solely on the outputs generated in response to selected inputs and execution
conditions.

Goal of Functional Testing :


The goal of Functional Testing is to verify whether your product meets the intended
functional specifications mentioned in your development documentation.

Testing Activities Included :


Test all the links in your webpages are working correctly and make sure there are
no broken links.
Links to be checked will include -
01. Outgoing links
02. Internal links
03. Anchor Links
04. MailTo Links
Test Forms are working as expected. This will include-
01. Scripting checks on the form are working as expected. For example- if a user
does not fill a mandatory field in a form an error message is shown.
02. Check default values are being populated.
03. Once submitted, the data in the forms is submitted to a live database or is
linked to a working email address.
04. Forms are optimally formatted for better readability.

Test Cookies are working as expected. Cookies are small files used by websites to
primarily remember active user sessions so you do not need to log in every time
you visit a website. Cookie Testing will include
01. Testing cookies (sessions) are deleted either when cache is cleared or when they
reach their expiry.
02. Delete cookies (sessions) and test that login credentials are asked for when you
next visit the site.

Test HTML and CSS to ensure that search engines can crawl your site easily. This
will include
01. Checking for Syntax Errors
02. Readable Color Schemas
03. Standard Compliance. Ensure standards such W3C, OASIS, IETF, ISO, ECMA, or
WS-I are followed.

Test business workflow- This will include


01. Testing your end - to - end workflow/ business scenarios which takes the user
through a series of web pages to complete.
02. Test negative scenarios as well, such that when a user executes an unexpected
step, appropriate error message or help is shown in your web application.

Functional Test Scenarios :


01. Test all the mandatory fields should be validated.
02. Test the asterisk sign should display for all the mandatory fields.
03. Test the system should not display the error message for optional fields.
04. Test that leap years are validated correctly & do not cause errors/miscalcula-
tions.
05. Test the numeric fields should not accept the alphabets and proper error
message should display.
06. Test for negative numbers if allowed for numeric fields.
07. Test division by zero should be handled properly for calculations.
08. Test the max length of every field to ensure the data is not truncated.
09. Test the pop up message (“This field is limited to 500 characters”) should dis-
play if the data reaches the maximum size of the field.
10. Test that a confirmation message should display for update and delete opera-
tions.
11. Test the amount values should display in currency format.
12. Test all input fields for special characters.
13. Test the timeout functionality.
14. Test the Sorting functionality. Test the Sorting functionality.
15. Test the functionality of the buttons available.
16. Test the Privacy Policy & FAQ is clearly defined and should be available for
users.
17. Test if any functionality fails the user gets redirected to the custom error
page.

usability testing
What is Usability Testing ?
01. Usability testing is nothing but the User-friendliness check.
02. In Usability testing, the application flow is tested so that a new user can un-
derstand the application easily.
03. Basically, system navigation is checked in Usability testing.

Goal of Usability Testing :


A Usability test establishes the ease of use and effectiveness of a product using a
standard Usability test practices.
Testing Activities Included :
Test the site Navigation:
01. Menus, buttons or Links to different pages on your site should be easily visible
and consistent on all webpages.
02. Test the Content.
03. Content should be legible with no spelling or grammatical errors.
04. Images if present should contain an “alt” text.

Usability Test Scenarios :


01. Web page content should be correct without any spelling or grammatical errors.
02. All fonts should be same as per the requirements.
03. All the text should be properly aligned.
04. All the error messages should be correct without any spelling or grammatical
errors and the error message should match with the field label.
05. Tool tip text should be there for every field.
06. All the fields should be properly aligned.
07. Enough space should be provided between field labels, columns, rows, and error
messages.
08. All the buttons should be in a standard format and size.
09. Home link should be there on every single page.
10. Disabled fields should be grayed out.
11. Check for broken links and images.
12. Confirmation message should be displayed for any kind of update and delete op-
eration.
13. Check the site on different resolutions (640 x 480, 600x800 etc.?)
14. Check the end user can run the system without frustration.
15. If there is an error message on submit, the information filled by the user should
be there.
16. Title should display on each web page
17. All fields (Textbox, dropdown, radio button etc) and buttons should be accessible
by keyboard shortcuts and the user should be able to perform all operations by
using keyboard.
18. Check if the dropdown data is not truncated due to the field size and also check
whether the data is hardcoded or managed via administrator.
interFace testing
Three areas to be tested here are - Application, Web and Database Server
01. Application: Test requests are sent correctly to the Database and output at the
client side is displayed correctly. Errors if any must be caught by the application
and must be only shown to the administrator and not the end user.
02. Web Server: Test Web server is handling all application requests without any
service denial.
03. Database Server: Make sure queries sent to the database give expected results.
Test system response when connection between the three layers (Application,
Web and Database) cannot be established and appropriate message is shown to the
end user.

Database testing

Database is one critical component of your web application and stress must be laid
to test it thoroughly. Testing activities will include-
01. Test if any errors are shown while executing queries.
02. Data Integrity is maintained while creating, updating or deleting data in data-
base.
03. Check response time of queries and fine tune them if necessary.
04. Test data retrieved from your database is shown accurately in your web appli-
cation.
To perform the Database testing, the tester should be aware of the below men-
tioned points:
01. The tester should understand the functional requirements, business logic, ap-
plication flow and database design thoroughly.
02. The tester should figure out the tables, triggers, store procedures, views and
cursors used for the application.
03. The tester should understand the logic of the triggers, store procedures, views
and cursors created.
04. The tester should figure out the tables which get affected when insert update
and delete (DML) operations are performed through the web or desktop appli-
cations.
Test Scenarios for Database Testing
01. Verify the database name: The database name should match with the specifica-
tions.
02. Verify the Tables, columns, column types and defaults. All things should match
with the specifications.
03. Verify whether the column allows a null or not.
04. Verify the Primary and foreign key of each table.
05. Verify the Stored Procedure.
06. Test whether the Stored procedure is installed or not.
07. Verify the Stored procedure name
08. Verify the parameter names, types and number of parameters.
09. Test the parameters if they are required or not.
10. Test the stored procedure by deleting some parameters
11. Test when the output is zero, the zero records should be affected.
12. Test the stored procedure by writing simple SQL queries.
13. Test whether the stored procedure returns the values
14. Test the stored procedure with sample input data.
15. Verify the behavior of each flag in the table.
16. Verify the data gets properly saved into the database after the each page submi-
sion.
17. Verify the data if the DML (Update, delete and insert) operations are performed.
18. Check the length of every field. The field length in the back end and front end
must be same.
19. Verify the database names of QA, UAT and production. The names should
beunique.
20. Verify the encrypted data in the database.
21. Verify the database size. Also test the response time of each query executed.
22. Verify the data displayed on the front end and make sure it is same in the back
end.
23. Verify the data validity by inserting the invalid data in the database.
24. Verify the Triggers.
compatibility testing

What is Compatibility Testing?


Compatibility testing is used to determine if your software is compatible with other
elements of a system with which it should operate, e.g. Browsers, Operating Sys-
tems, or hardware.

Goal of Compatibility Testing :


The purpose of Compatibility testing is to evaluate how well software performs in
a particular browser, Operating Systems, hardware or software. Compatibility tests
ensure that your web application displays correctly across different devices.

Testing Activities Included :


Browser Compatibility Test: Same website in different browsers will display dif-
ferently. You need to test if your web application is being displayed correctly across
browsers, JavaScript, AJAX and authentication is working fine. You may also check
for Mobile Browser Compatibility.

The rendering of web elements like buttons, text fields etc. changes with change
in Operating System. Make sure your website works fine for various combination
of Operating systems such as Windows, Linux, Mac and Browsers such as Firefox,
Internet Explorer, Safari etc.

Compatibility Test Scenarios :


01. Test the website in different browsers (IE, Firefox, Chrome, Safari and Opera)
and ensure the website is displaying properly.
02. Test the HTML version being used is compatible with appropriate browser
versions.
03. Test the images display correctly in different browsers.
04. Test the fonts are usable in different browsers.
05. Test the java script code is usable in different browsers.
06. Test the Animated GIF's across different browsers.
perFormance testing
What is Performance Testing ?
Performance Testing is conducted to evaluate the compliance of a system or
component with specified performance requirements.

Testing Activities Included :


01. Website application response times at different connection speeds.
02. Load test your web application to determine its behavior under normal and
peak loads.
03. Stress test your web site to determine its break point when pushed to be-
yond normal loads at peak time.
04. Test if a crash occurs due to peak load, how does the site recover from such
an event.
05. Make sure optimization techniques like gzip compression, browser and
server side cache enabled to reduce load times.

General Test Scenarios :


01. To determine the performance, stability and scalability of an application
under different load conditions.
02. To determine if the current architecture can support the application at
peak user levels.
03. To determine which configuration sizing provides the best performance
level.
04. To identify application and infrastructure bottlenecks.
05. To determine if the new version of the software adversely had an impact
on response time.
06. To evaluate product and/or hardware to determine if it can handle project-
ed load volumes.
security testing
Security Testing involves the test to identify any flaws and gaps from a security
point of view.

Test Scenarios for Security Testing :


01. Verify the web page which contains important data like password, credit card
numbers, secret answers for security question etc should be submitted via
HTTPS (SSL).
02. Verify the important information like password, credit card numbers etc should
display in encrypted format.
03. Verify password rules are implemented on all authentication pages like Regis-
tration, forgot password, change password.
04. Verify if the password is changed the user should not be able to login with the
old password.
05. Verify the error messages should not display any important information.
06. Verify if the user is logged out from the system or user session was expired, the
user should not be able to navigate the site.
07. Verify to access the secured and non secured web pages directly without login.
08. Verify the “View Source code” option is disabled and should not be visible to the
user.
09. Verify the user account gets locked out if the user is entering the wrong pass-
word several times.
10. Verify the cookies should not store passwords.
11. Verify if, any functionality is not working, the system should not display any ap-
plication, server, or database information. Instead, it should display the custom
error page.
12. Verify the SQL injection attacks.
13. Verify the user roles and their rights. For Example The requestor should not be
able to access the admin page.
14. Verify the important operations are written in log files, and that information
should be traceable.
15. Verify the session values are in an encrypted format in the address bar.
16. Verify the cookie information is stored in encrypted format.
17. Verify the application for Brute Force Attacks.
SQL
(Notes by Apna College)

What is Database?
Database is a collection of interrelated data.

What is DBMS?
DBMS (Database Management System) is software used to create, manage, and organize
databases.

What is RDBMS?
● RDBMS (Relational Database Management System) - is a DBMS based on the
concept of tables (also called relations).
● Data is organized into tables (also known as relations) with rows (records) and
columns (attributes).
● Eg - MySQL, PostgreSQL, Oracle etc.

What is SQL?
SQL is Structured Query Language - used to store, manipulate and retrieve data from
RDBMS.
(It is not a database, it is a language used to interact with database)

We use SQL for CRUD Operations :


● CREATE - To create databases, tables, insert tuples in tables etc
● READ - To read data present in the database.
● UPDATE - Modify already inserted data.
● DELETE - Delete database, table or specific data point/tuple/row or multiple rows.

*Note - SQL keywords are NOT case sensitive. Eg: select is the same as SELECT in SQL.

SQL v/s MySQL


SQL is a language used to perform CRUD operations in Relational DB, while MySQL is a
RDBMS that uses SQL.
SQL Data Types
In SQL, data types define the kind of data that can be stored in a column or variable.

To See all data types of MYSQL, visit :


https://dev.mysql.com/doc/refman/8.0/en/data-types.html

Here are the frequently used SQL data types:

DATATYPE DESCRIPTION USAGE

CHAR string(0-255), can store characters of fixed length CHAR(50)

VARCHAR string(0-255), can store characters up to given length VARCHAR(50)

BLOB string(0-65535), can store binary large object BLOB(1000)

INT integer( -2,147,483,648 to 2,147,483,647 ) INT

TINYINT integer(-128 to 127) TINYINT

BIGINT integer( -9,223,372,036,854,775,808 to BIGINT


9,223,372,036,854,775,807 )

BIT can store x-bit values. x can range from 1 to 64 BIT(2)

FLOAT Decimal number - with precision to 23 digits FLOAT

DOUBLE Decimal number - with 24 to 53 digits DOUBLE

BOOLEAN Boolean values 0 or 1 BOOLEAN

DATE date in format of YYYY-MM-DD ranging from DATE


1000-01-01 to 9999-12-31

TIME HH:MM:SS TIME

YEAR year in 4 digits format ranging from 1901 to 2155 YEAR

*Note - CHAR is for fixed length & VARCHAR is for variable length strings. Generally,
VARCHAR is better as it only occupies necessary memory & works more efficiently.

We can also use UNSIGNED with datatypes when we only have positive values to add.
Eg - UNSIGNED INT

Types of SQL Commands:


1. DQL (Data Query Language) : Used to retrieve data from databases. (SELECT)

2. DDL (Data Definition Language) : Used to create, alter, and delete database objects
like tables, indexes, etc. (CREATE, DROP, ALTER, RENAME, TRUNCATE)

3. DML (Data Manipulation Language): Used to modify the database. (INSERT,


UPDATE, DELETE)

4. DCL (Data Control Language): Used to grant & revoke permissions. (GRANT,
REVOKE)

5. TCL (Transaction Control Language): Used to manage transactions. (COMMIT,


ROLLBACK, START TRANSACTIONS, SAVEPOINT)

1. Data Definition Language (DDL)

Data Definition Language (DDL) is a subset of SQL (Structured Query Language)


responsible for defining and managing the structure of databases and their objects.

DDL commands enable you to create, modify, and delete database objects like tables,
indexes, constraints, and more.

Key DDL Commands are:

● CREATE TABLE:

○ Used to create a new table in the database.


○ Specifies the table name, column names, data types, constraints, and more.
○ Example:
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50),
salary DECIMAL(10, 2));

● ALTER TABLE:

○ Used to modify the structure of an existing table.


○ You can add, modify, or drop columns, constraints, and more.
○ Example: ALTER TABLE employees ADD COLUMN email VARCHAR(100);

● DROP TABLE:

○ Used to delete an existing table along with its data and structure.
○ Example: DROP TABLE employees;
● CREATE INDEX:

○ Used to create an index on one or more columns in a table.


○ Improves query performance by enabling faster data retrieval.
○ Example: CREATE INDEX idx_employee_name ON employees (name);

● DROP INDEX:

○ Used to remove an existing index from a table.


○ Example: DROP INDEX idx_employee_name;

● CREATE CONSTRAINT:

○ Used to define constraints that ensure data integrity.


○ Constraints include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL,
and CHECK.
○ Example: ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN
KEY (customer_id) REFERENCES customers(id);

● DROP CONSTRAINT:

○ Used to remove an existing constraint from a table.


○ Example: ALTER TABLE orders DROP CONSTRAINT fk_customer;

● TRUNCATE TABLE:

○ Used to delete the data inside a table, but not the table itself.
○ Syntax – TRUNCATE TABLE table_name

2. DATA QUERY/RETRIEVAL LANGUAGE (DQL or DRL)

DQL (Data Query Language) is a subset of SQL focused on retrieving data from databases.

The SELECT statement is the foundation of DQL and allows us to extract specific columns
from a table.

● SELECT:

The SELECT statement is used to select data from a database.


Syntax: SELECT column1, column2, ... FROM table_name;

Here, column1, column2, ... are the field names of the table.

If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;

Ex: SELECT CustomerName, City FROM Customers;

● WHERE:

The WHERE clause is used to filter records.

Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;

Ex: SELECT * FROM Customers WHERE Country='Mexico';

Operators used in WHERE are:

= : Equal
> : Greater than
< : Less than
>= : Greater than or equal
<= : Less than or equal
<> : Not equal.

Note: In some versions of SQL this operator may be written as !=

● AND, OR and NOT:

- The WHERE clause can be combined with AND, OR, and NOT operators.

- The AND and OR operators are used to filter records based on more than one
condition:

- The AND operator displays a record if all the conditions separated by AND are
TRUE.

- The OR operator displays a record if any of the conditions separated by OR is TRUE.

- The NOT operator displays a record if the condition(s) is NOT TRUE.

Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND
condition3 ...;

SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR


condition3 ...;

SELECT column1, column2, ... FROM table_name WHERE NOT condition;

Example:

SELECT * FROM Customers WHERE Country=’India’ AND City=’Japan’;

SELECT * FROM Customers WHERE Country=’America’ AND (City=’India’ OR


City=’Korea’);

● DISTINCT:

Removes duplicate rows from query results.

Syntax: SELECT DISTINCT column1, column2 FROM table_name;

● LIKE:

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

- The percent sign (%) represents zero, one, or multiple characters


- The underscore sign (_) represents one, single character

Example: SELECT * FROM employees WHERE first_name LIKE 'J%';

WHERE CustomerName LIKE 'a%'


- Finds any values that start with "a"

WHERE CustomerName LIKE '%a'


- Finds any values that end with "a"

WHERE CustomerName LIKE '%or%'


- Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'


- Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%'
- Finds any values that start with "a" and are at least 2 characters in length

WHERE CustomerName LIKE 'a__%'


- Finds any values that start with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'


- Finds any values that start with "a" and ends with "o"

● IN:

Filters results based on a list of values in the WHERE clause.

Example: SELECT * FROM products WHERE category_id IN (1, 2, 3);

● BETWEEN:

Filters results within a specified range in the WHERE clause.

Example: SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND


'2023-06-30';

● IS NULL:

Checks for NULL values in the WHERE clause.

Example: SELECT * FROM customers WHERE email IS NULL;

● AS:

Renames columns or expressions in query results.

Example: SELECT first_name AS "First Name", last_name AS "Last Name" FROM


employees;

● ORDER BY

The ORDER BY clause allows you to sort the result set of a query based on one or more
columns.

Basic Syntax:

- The ORDER BY clause is used after the SELECT statement to sort query results.
- Syntax: SELECT column1, column2 FROM table_name ORDER BY column1
[ASC|DESC];

Ascending and Descending Order:

- By default, the ORDER BY clause sorts in ascending order (smallest to largest).


- You can explicitly specify descending order using the DESC keyword.
- Example: SELECT product_name, price FROM products ORDER BY price DESC;

Sorting by Multiple Columns:

- You can sort by multiple columns by listing them sequentially in the ORDER BY
clause.
- Rows are first sorted based on the first column, and for rows with equal values,
subsequent columns are used for further sorting.
- Example: SELECT first_name, last_name FROM employees ORDER BY last_name,
first_name;

Sorting by Expressions:

- It's possible to sort by calculated expressions, not just column values.


- Example: SELECT product_name, price, price * 1.1 AS discounted_price FROM
products ORDER BY discounted_price;

Sorting NULL Values:

- By default, NULL values are considered the smallest in ascending order and the
largest in descending order.
- You can control the sorting behaviour of NULL values using the NULLS FIRST or
NULLS LAST options.
- Example: SELECT column_name FROM table_name ORDER BY column_name
NULLS LAST;

Sorting by Position:

- Instead of specifying column names, you can sort by column positions in the ORDER
BY clause.
- Example: SELECT product_name, price FROM products ORDER BY 2 DESC, 1
ASC;

● GROUP BY

The GROUP BY clause in SQL is used to group rows from a table based on one or more
columns.

Syntax:
- The GROUP BY clause follows the SELECT statement and is used to group rows
based on specified columns.

- Syntax: SELECT column1, aggregate_function(column2) FROM table_name


GROUP BY column1;

- Aggregation Functions:
○ Aggregation functions (e.g., COUNT, SUM, AVG, MAX, MIN) are often used
with GROUP BY to calculate values for each group.
○ Example: SELECT department, AVG(salary) FROM employees GROUP BY
department;
- Grouping by Multiple Columns:

○ You can group by multiple columns by listing them in the GROUP BY clause.
○ This creates a hierarchical grouping based on the specified columns.
○ Example: SELECT department, gender, AVG(salary) FROM employees
GROUP BY department, gender;

- HAVING Clause:

○ The HAVING clause is used with GROUP BY to filter groups based on


aggregate function results.
○ It's similar to the WHERE clause but operates on grouped data.
○ Example: SELECT department, AVG(salary) FROM employees GROUP BY
department HAVING AVG(salary) > 50000;

- Combining GROUP BY and ORDER BY:

○ You can use both GROUP BY and ORDER BY in the same query to control
the order of grouped results.
○ Example: SELECT department, COUNT(*) FROM employees GROUP BY
department ORDER BY COUNT(*) DESC;

● AGGREGATE FUNCTIONS

These are used to perform calculations on groups of rows or entire result sets. They provide
insights into data by summarising and processing information.

Common Aggregate Functions:

- COUNT():
Counts the number of rows in a group or result set.

- SUM():
Calculates the sum of numeric values in a group or result set.

- AVG():
Computes the average of numeric values in a group or result set.

- MAX():
Finds the maximum value in a group or result set.

- MIN():
Retrieves the minimum value in a group or result set.

3. DATA MANIPULATION LANGUAGE

Data Manipulation Language (DML) in SQL encompasses commands that manipulate data
within a database. DML allows you to insert, update, and delete records, ensuring the
accuracy and currency of your data.

● INSERT:

- The INSERT statement adds new records to a table.


- Syntax: INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2,
...);

- Example: INSERT INTO employees (first_name, last_name, salary) VALUES ('John',


'Doe', 50000);

● UPDATE:

- The UPDATE statement modifies existing records in a table.


- Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;
- Example: UPDATE employees SET salary = 55000 WHERE first_name = 'John';

● DELETE:

- The DELETE statement removes records from a table.


- Syntax: DELETE FROM table_name WHERE condition;
- Example: DELETE FROM employees WHERE last_name = 'Doe';

4. Data Control Language (DCL)


Data Control Language focuses on the management of access rights, permissions, and
security-related aspects of a database system.

DCL commands are used to control who can access the data, modify the data, or perform
administrative tasks within a database.

DCL is an important aspect of database security, ensuring that data remains protected and
only authorised users have the necessary privileges.

There are two main DCL commands in SQL: GRANT and REVOKE.

1. GRANT:

The GRANT command is used to provide specific privileges or permissions to users or roles.
Privileges can include the ability to perform various actions on tables, views, procedures,
and other database objects.

Syntax:

GRANT privilege_type
ON object_name
TO user_or_role;

In this syntax:

● privilege_type refers to the specific privilege or permission being granted (e.g.,


SELECT, INSERT, UPDATE, DELETE).
● object_name is the name of the database object (e.g., table, view) to which the
privilege is being granted.
● user_or_role is the name of the user or role that is being granted the privilege.

Example: Granting SELECT privilege on a table named "Employees" to a user named


"Analyst":

GRANT SELECT ON Employees TO Analyst;

2. REVOKE:

The REVOKE command is used to remove or revoke specific privileges or permissions that
have been previously granted to users or roles.

Syntax:

REVOKE privilege_type
ON object_name
FROM user_or_role;

In this syntax:

● privilege_type is the privilege or permission being revoked.


● object_name is the name of the database object from which the privilege is being
revoked.
● user_or_role is the name of the user or role from which the privilege is being
revoked.

Example: Revoking the SELECT privilege on the "Employees" table from the "Analyst" user:

REVOKE SELECT ON Employees FROM Analyst;

DCL and Database Security:

DCL plays a crucial role in ensuring the security and integrity of a database system.

By controlling access and permissions, DCL helps prevent unauthorised users from
tampering with or accessing sensitive data. Proper use of GRANT and REVOKE commands
ensures that only users who require specific privileges can perform certain actions on
database objects.

5. Transaction Control Language (TCL)

Transaction Control Language (TCL) deals with the management of transactions within a
database.
TCL commands are used to control the initiation, execution, and termination of transactions,
which are sequences of one or more SQL statements that are executed as a single unit of
work.
Transactions ensure data consistency, integrity, and reliability in a database by grouping
related operations together and either committing or rolling back changes based on the
success or failure of those operations.

There are three main TCL commands in SQL: COMMIT, ROLLBACK, and SAVEPOINT.

1. COMMIT:

The COMMIT command is used to permanently save the changes made during a
transaction.
It makes all the changes applied to the database since the last COMMIT or ROLLBACK
command permanent.
Once a COMMIT is executed, the transaction is considered successful, and the changes are
made permanent.

Example: Committing changes made during a transaction:

UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';

COMMIT;

2. ROLLBACK:

The ROLLBACK command is used to undo changes made during a transaction.


It reverts all the changes applied to the database since the transaction began.

ROLLBACK is typically used when an error occurs during the execution of a transaction,
ensuring that the database remains in a consistent state.

Example: Rolling back changes due to an error during a transaction:

BEGIN;

UPDATE Inventory
SET Quantity = Quantity - 10
WHERE ProductID = 101;

-- An error occurs here

ROLLBACK;

3. SAVEPOINT:

The SAVEPOINT command creates a named point within a transaction, allowing you to set a
point to which you can later ROLLBACK if needed.

SAVEPOINTs are useful when you want to undo part of a transaction while preserving other
changes.

Syntax: SAVEPOINT savepoint_name;

Example: Using SAVEPOINT to create a point within a transaction:

BEGIN;
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 123;

SAVEPOINT before_withdrawal;

UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 456;

-- An error occurs here

ROLLBACK TO before_withdrawal;

-- The first update is still applied

COMMIT;

TCL and Transaction Management:

Transaction Control Language (TCL) commands are vital for managing the integrity and
consistency of a database's data.
They allow you to group related changes into transactions, and in the event of errors, either
commit those changes or roll them back to maintain data integrity.
TCL commands are used in combination with Data Manipulation Language (DML) and other
SQL commands to ensure that the database remains in a reliable state despite unforeseen
errors or issues.

JOINS

In a DBMS, a join is an operation that combines rows from two or more tables based on a
related column between them.
Joins are used to retrieve data from multiple tables by linking them together using a common
key or column.

Types of Joins:
1. Inner Join
2. Outer Join
3. Cross Join
4. Self Join

1) Inner Join

An inner join combines data from two or more tables based on a specified condition, known
as the join condition.
The result of an inner join includes only the rows where the join condition is met in all
participating tables.
It essentially filters out non-matching rows and returns only the rows that have matching
values in both tables.

Syntax:

SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Here:

● columns refers to the specific columns you want to retrieve from the tables.
● table1 and table2 are the names of the tables you are joining.
● column is the common column used to match rows between the tables.
● The ON clause specifies the join condition, where you define how the tables are
related.

Example: Consider two tables: Customers and Orders.

Customers Table:

CustomerID CustomerName

1 Alice

2 Bob

3 Carol

Orders Table:

OrderID CustomerID Product


101 1 Laptop

102 3 Smartphone

103 2 Headphones

Inner Join Query:

SELECT Customers.CustomerName, Orders.Product


FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result:

CustomerName Product

Alice Laptop

Bob Headphones

Carol Smartphone

2) Outer Join

Outer joins combine data from two or more tables based on a specified condition, just like
inner joins. However, unlike inner joins, outer joins also include rows that do not have
matching values in both tables.
Outer joins are particularly useful when you want to include data from one table even if there
is no corresponding match in the other table.

Types:

There are three types of outer joins: left outer join, right outer join, and full outer join.

1. Left Outer Join (Left Join):

A left outer join returns all the rows from the left table and the matching rows from the right
table.
If there is no match in the right table, the result will still include the left table's row with NULL
values in the right table's columns.

Example:

SELECT Customers.CustomerName, Orders.Product


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result:

CustomerName Product

Alice Laptop

Bob Headphones

Carol Smartphone

NULL Monitor

In this example, the left outer join includes all rows from the Customers table.

Since there is no matching customer for the order with OrderID 103 (Monitor), the result
includes a row with NULL values in the CustomerName column.

2. Right Outer Join (Right Join):

A right outer join is similar to a left outer join, but it returns all rows from the right table and
the matching rows from the left table.

If there is no match in the left table, the result will still include the right table's row with NULL
values in the left table's columns.

Example: Using the same Customers and Orders tables.

SELECT Customers.CustomerName, Orders.Product


FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result:
CustomerName Product

Alice Laptop

Carol Smartphone

Bob Headphones

NULL Keyboard

Here, the right outer join includes all rows from the Orders table. Since there is no matching
order for the customer with CustomerID 4, the result includes a row with NULL values in the
CustomerName column.

3. Full Outer Join (Full Join):

A full outer join returns all rows from both the left and right tables, including matches and
non-matches.

If there's no match, NULL values appear in columns from the table where there's no
corresponding value.

Example: Using the same Customers and Orders tables.

SELECT Customers.CustomerName, Orders.Product


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result:

CustomerName Product

Alice Laptop

Bob Headphones

Carol Smartphone
NULL Monitor

NULL Keyboard

In this full outer join example, all rows from both tables are included in the result. Both
non-matching rows from the Customers and Orders tables are represented with NULL
values.

3) Cross Join

A cross join, also known as a Cartesian product, is a type of join operation in a Database
Management System (DBMS) that combines every row from one table with every row from
another table.

Unlike other join types, a cross join does not require a specific condition to match rows
between the tables. Instead, it generates a result set that contains all possible combinations
of rows from both tables.

Cross joins can lead to a large result set, especially when the participating tables have many
rows.

Syntax:

SELECT columns
FROM table1
CROSS JOIN table2;

In this syntax:

● columns refers to the specific columns you want to retrieve from the cross-joined
tables.
● table1 and table2 are the names of the tables you want to combine using a cross
join.

Example: Consider two tables: Students and Courses.

Students Table:

StudentID StudentName

1 Alice
2 Bob

Courses Table:

CourseID CourseName

101 Maths

102 Science

Cross Join Query:

SELECT Students.StudentName, Courses.CourseName


FROM Students
CROSS JOIN Courses;

Result:

StudentName CourseName

Alice Maths

Alice Science

Bob Maths

Bob Science

In this example, the cross join between the Students and Courses tables generates all
possible combinations of rows from both tables. As a result, each student is paired with each
course, leading to a total of four rows in the result set.

4) Self Join

A self join involves joining a table with itself.

This technique is useful when a table contains hierarchical or related data and you need to
compare or analyse rows within the same table.
Self joins are commonly used to find relationships, hierarchies, or patterns within a single
table.

In a self join, you treat the table as if it were two separate tables, referring to them with
different aliases.

Syntax:

The syntax for performing a self join in SQL is as follows:

SELECT columns
FROM table1 AS alias1
JOIN table1 AS alias2 ON alias1.column = alias2.column;

In this syntax:
● columns refers to the specific columns you want to retrieve from the self-joined table.
● table1 is the name of the table you're joining with itself.
● alias1 and alias2 are aliases you assign to the table instances for differentiation.
● column is the column you use as the join condition to link rows from the same table.

Example: Consider an Employees table that contains information about employees and their
managers.

Employees Table:

EmployeeID EmployeeName ManagerID

1 Alice 3

2 Bob 3

3 Carol NULL

4 David 1

Self Join Query:

SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager


FROM Employees AS e1
JOIN Employees AS e2 ON e1.ManagerID = e2.EmployeeID;

Result:

Employee Manager
Alice Carol

Bob Carol

David Alice

In this example, the self join is performed on the Employees table to find the relationship
between employees and their managers. The join condition connects the ManagerID column
in the e1 alias (representing employees) with the EmployeeID column in the e2 alias
(representing managers).

SET OPERATIONS

Set operations in SQL are used to combine or manipulate the result sets of multiple SELECT
queries.
They allow you to perform operations similar to those in set theory, such as union,
intersection, and difference, on the data retrieved from different tables or queries.

Set operations provide powerful tools for managing and manipulating data, enabling you to
analyse and combine information in various ways.

There are four primary set operations in SQL:

● UNION
● INTERSECT
● EXCEPT (or MINUS)
● UNION ALL

1. UNION:

The UNION operator combines the result sets of two or more SELECT queries into a single
result set.
It removes duplicates by default, meaning that if there are identical rows in the result sets,
only one instance of each row will appear in the final result.

Example:

Assume we have two tables: Customers and Suppliers.


Customers Table:

CustomerID CustomerName

1 Alice

2 Bob

Suppliers Table:

SupplierID SupplierName

101 SupplierA

102 SupplierB

UNION Query:

SELECT CustomerName FROM Customers


UNION
SELECT SupplierName FROM Suppliers;

Result:

CustomerName

Alice

Bob

SupplierA

SupplierB

2. INTERSECT:

The INTERSECT operator returns the common rows that exist in the result sets of two or
more SELECT queries.

It only returns distinct rows that appear in all result sets.


Example: Using the same tables as before.

SELECT CustomerName FROM Customers


INTERSECT
SELECT SupplierName FROM Suppliers;

Result:

CustomerName

In this example, there are no common names between customers and suppliers, so the
result is an empty set.

3. EXCEPT (or MINUS):

The EXCEPT operator (also known as MINUS in some databases) returns the distinct rows
that are present in the result set of the first SELECT query but not in the result set of the
second SELECT query.

Example: Using the same tables as before.

SELECT CustomerName FROM Customers


EXCEPT
SELECT SupplierName FROM Suppliers;

Result:

CustomerName

Alice

Bob

In this example, the names "Alice" and "Bob" are customers but not suppliers, so they
appear in the result set.

4. UNION ALL:

The UNION ALL operator performs the same function as the UNION operator but does not
remove duplicates from the result set. It simply concatenates all rows from the different
result sets.
Example: Using the same tables as before.

SELECT CustomerName FROM Customers


UNION ALL
SELECT SupplierName FROM Suppliers;

Result:

CustomerName

Alice

Bob

SupplierA

SupplierB

Difference between Set Operations and Joins

Aspect Set Operations Joins

Combine data from related


Manipulate result sets based on
Purpose tables based on specified
set theory principles.
conditions.
Tables that are related by
Data Source Result sets of SELECT queries.
common columns.

Combine rows from different Combine rows from different

Combining Rows result sets. May remove tables based on specified

duplicates. conditions.

Require the SELECT queries to


Can combine columns from
have the same number of output
Output Columns different tables, regardless of
columns and compatible data
data types or column numbers.
types.

Common UNION, INTERSECT, EXCEPT INNER JOIN, LEFT JOIN, RIGHT

Operations (MINUS). JOIN, FULL JOIN.

Conditional No specific join conditions are Require specified join conditions

Requirements required. for combining data.

Joins do not inherently handle


Handling UNION removes duplicates by
duplicates; it depends on the join
Duplicates default.
type and data.
Useful for combining and Used to retrieve and relate data

Usage Scenarios analysing related data from from different tables based on

different queries or tables. their relationships.

Result sets may have different Result sets can have different
Result Set
column names, but data types and column names, data types, and
Structure
counts must match. counts.

Joins can be more complex and


Performance Generally faster and less complex
resource-intensive, especially for
Considerations than joins.
larger datasets.

SUB QUERIES

Subqueries, also known as nested queries or inner queries, allow you to use the result of
one query (the inner query) as the input for another query (the outer query).

Subqueries are often used to retrieve data that will be used for filtering, comparison, or
calculation within the context of a larger query.

They are a way to break down complex tasks into smaller, manageable steps.

Syntax:

SELECT columns
FROM table
WHERE column OPERATOR (SELECT column FROM table WHERE condition);

In this syntax:

● columns refers to the specific columns you want to retrieve from the outer query.
● table is the name of the table you're querying.
● column is the column you're applying the operator to in the outer query.
● OPERATOR is a comparison operator such as =, >, <, IN, NOT IN, etc.
● (SELECT column FROM table WHERE condition) is the subquery that provides the
input for the comparison.

Example: Consider two tables: Products and Orders.

Products Table:

ProductID ProductName Price

1 Laptop 1000

2 Smartphone 500

3 Headphones 50

Orders Table:

OrderID ProductID Quantity

101 1 2

102 3 1

For Example: Retrieve the product names and quantities for orders with a total cost greater
than the average price of all products.

SELECT ProductName, Quantity


FROM Products
WHERE Price * Quantity > (SELECT AVG(Price) FROM Products);

Result:

ProductName Quantity
Laptop 2

Differences Between Subqueries and Joins:

Aspect Subqueries Joins

Retrieve data for filtering,


comparison, or calculation Combine data from related tables
Purpose
within the context of a larger based on specified conditions.
query.

Result of one query used as


Data Source Data from multiple related tables.
input for another query.

Not used for combining rows; Combines rows from different tables
Combining Rows
used to filter or evaluate data. based on specified join conditions.

Subqueries return scalar


Result Set Joins return multi-column result
values, single-column results,
Structure sets.
or small result sets.

Subqueries can be slower and


Performance Joins can be more efficient for
less efficient, especially when
Considerations combining data from multiple tables.
dealing with large datasets.

Joins can become complex, but are


Subqueries can be easier to
more suited for handling large-scale
Complexity understand for simple tasks or
data retrieval and combination
smaller datasets.
tasks.

Subqueries can be used in


Joins are primarily used in the
Versatility various clauses: WHERE,
FROM clause for combining tables.
FROM, HAVING, etc.
Test Cases

Test Scenarios

Test Script
Test
Scenarios
A Test Scenario is any functionality that
can be tested. It is also called Test
Condition or Test Possibility.

01
Test
Cases
It is a document that contains the steps
that have to be executed; it has been
planned earlier.

02
Test
Script
It is written in a programming language
and it’s a short program used to test
part of the functionality of the software
system. In other words, a written set of
steps that should be performed
manually.

03
Software Testing

Cyber Security

We provide a complete solution


for your Testing needs
Get in touch with us today

www.precisetestingsolution.com
Email Sentences and Phrases
in different situations

20 Sentences and Phrases


for Beginning an Email
1 Thank you for your message/email/phone call.
2 I hope you are doing well.
3 I hope you had a great weekend.
4 I hope this finds you well.
5 Just checking in.
6 Thanks again for your help.
7 It was great talking to you.
8 It was great meeting you.
9 Thanks for the additional info.
10 Just wanted to send you a quick note to…
11 How is everything?
12 Thanks for the quick response.
13 Thanks for your help with…
14 I have a quick question.
15 I have a quick request.
16 Thanks for the update.
17 Just checking in to make sure that…
18 I wanted to reach out to you because…
19 I am looking forward to…
20 It is great to hear from you.

Design and preparation by Eng. \ Mustafa Gouda


20 phrases for closing an email
Expressions for thanking
1 Thank you for your help. / time / assistance / support
2 I really appreciate the help. / time / assistance / support you’ve given me
3 Thank you once more for your help in this matter.
Expressions with a future focus
1 I look forward to hearing from you soon / meeting you next Tuesday.
2 I look forward to seeing you soon.
3 I’m looking forward to your reply.
4 We hope that we may continue to rely on your valued custom.
5 We look forward to a successful working relationship in the future.
6 Please advise as necessary.
7 I would appreciate your immediate attention to this matter.
Expressions for showing them you want to help
1 If I can be of assistance, please do not hesitate to contact me.
2 If you require any further information, feel free to contact me.
3 If you require any further information, let me know.
4 Please feel free to contact me if you need any further information.
5 Please let me know if you have any questions.
6 I hope the above is useful to you.
Should you need any further information, please do not hesitate to contact
7
me.
8 Please contact me if there are any problems.
9 Let me know if you need anything else
10 Drop me a line if I can do anything else for you.

Basics Email
Design and preparation by Eng. \ Mustafa Gouda
Formal / Neutral Informal
Dear Mr/Ms/Mrs Dupuis Hi/Hello Mary
Name
Dear Mary Mary,... (or no name at all)
Thank you for your email of ... Thanks for your email.
Previous
Further to your last email, ... Re your email, ...
contact
I apologize for not getting in contact with Sorry I haven’t written for ages, but I’ve
you before now. been really busy.
I am writing in connection with ... Just a short note about ...
I am writing with regard to ... I’m writing about ...
Reason for
In reply to your email, here are ... Here’s the ... you wanted.
writing
Your name was given to me by ... I got your name from ...
We would like to point out that ... Please note that ...
I’m writing to let you know that ... Just a note to say ...
Giving We are able to confirm that ... We can confirm that ...
information I am delighted to tell you that ... Good news!
We regret to inform you that ... Unfortunately, ...
Please find attached my report. I’ve attached ...
Attachments
I’m sending you ... as a pdf file. Here is the ... you wanted.
Could you give me some information
Can you tell me a little more about ...
Asking for about ...
I’d like to know ...
information I would like to know ...
Please send me ...
I’m interested in receiving/finding out ...
I’d be grateful if you could ...
Please could you ...
I wonder if you could ...
Could you ...?
Requests Do you think I could have ... ?
Can I have ...?
Thank you in advance for your help in this
I’d appreciate your help on this.
matter.
I will ... I’ll ...
Promising
I’ll investigate the matter. I’ll look into it.
action
I will contact you again shortly. I’ll get back to you soon.
Would you like me to ...?
Do you want me to ...?
If you wish, I would be happy to ...
Offering help Shall I ...?
Let me know whether you would like me
Let me know if you’d like me to ...
to ...
Thank you for your help.
Thanks again for ...
Do not hesitate to contact us again if you
Final Let me know if you need anything else.
require any further information.
comments Just give me a call if you have any
Please feel free to contact me if you have
questions. My number is ...
any questions. My direct line is ...
I’m looking forward to ... (+ ing) Looking forward to ... (+ ing)
Give my regards to ... Best wishes to ..
Close
Best wishes Speak to/see you soon.
Regards Bye (for now)/All the best

Negotiating a project
Asking for information What are your usual charges (fees/rates) for ...?

Design and preparation by Eng. \ Mustafa Gouda


Can you give me some more information about ...?
Requests Do you think you could ...? / Would you be able to ...?
Emphasizing a main point My main concern at this stage is ... / The main thing for me is ...
How do you think we should deal with this?
Asking for a suggestion
What do you think is the best way forward?
Making a suggestion Why don’t you ...? / What about if we ...?
I understand what you’re saying about ... (but ... )
Negotiating: being firm
I can see what you’re saying, but ...
Negotiating: being flexible We would be prepared to ... (if ...) / I am willing to ... (if ...)
Okay, I’m happy with that for now.
Negotiating: agreeing
That’s fine.
I’ll be in touch again soon with more details.
Next steps
Let’s talk next week and see how things are going.
I look forward to working with you.
Closing I’m sorry that we couldn’t use your services this time, but I hope there will
be another opportunity.

Checking understanding
Did you get my last message sent on ...?
Technical Sorry, you forgot to attach the file. Can you send it again?
problems I got your email, but I can’t open the attachment.
Did you mean to send this? I don’t want to open it in case it’s got a virus.
I’m not sure what you meant by ...? could you clarify?
Asking for
Which ... do you mean? / Are you sure about that?
clarification
I don’t understand this point. Can you explain in a little more detail?
Sorry, what I meant was ..., not ...
Giving I thought ..., but I may be wrong. / I’ll check and get back to you.
clarification The correct information is given below. Please amend your records accordingly.
Sorry, forget my last email. You’re right.
Close I hope this clarifies the situation. / Get back to me if there’s anything else.

Arrangements Meetings
Formal / Neutral Informal
I’m writing to arrange a time for our
Reason for Just a quick note to arrange a time to meet.
meeting.
writing When would suit you?
What time would be convenient for you?
Suggesting Could we meet on (day) in the (morning) at How about (day) at (time)?
time/place (time)? Are you free sometime next week?
I would be able to attend the meeting on
I’m free Thursday am.
Saying when Thursday morning.
I won’t be around until after lunch.
you are/ are I’m out of the office until 2pm.
Any time after hat is okay.
not free Any time after that would be fine.
Sorry, can’t make it next Monday.
I’m afraid I can’t manage next Monday.
I’d like to confirm ... Thursday is good for me.
Confirming That’s fine. I will call/email you tomorrow to That should be okay. I’ll get back to you if
confirm the details. there’s a problem.
This is to let you know that I will not be able Re our meeting next week, I’m afraid I can’t
Changing to attend the next meeting next Thursday. make Thursday.
arrangements I wonder if we could move it to ...? How about ... instead?
I apologize for any inconvenience caused. Sorry for the inconvenience.
I look forward to meeting you in Brussels.
See you in Brussels.
Close Let me know if you need to change the
Give me a call if anything changes.
arrangements.

Invitations
Design and preparation by Eng. \ Mustafa Gouda
Formal / Neutral Informal
We would be very pleased if you could come
to ...
I’m writing to invite you to ...
I would like to invite you to ... / attend our ...
Inviting Would you like to come to ...?
Please let me know if you will be able to
Please let me know if you can make it.
attend.

Before the meeting it would be useful if you


could prepare ... Please prepare ... before the meeting.
Prepare
It would be helpful if you could bring ... Please bring to the meeting ...

Thank you for your kind invitation.


Thanks a lot for the invitation.
The date you suggest is fine.
The date’s fine for me.
Accepting I would be delighted to attend the meeting. I
I’d love to come to the meeting. It sounds like
am sure it will be very useful.
a great idea.
Thank you for your kind invitation.
Unfortunately, I have another appointment on Thanks a lot for your kind invitation.
that day. Please accept my apologies. Unfortunately, I have something else in my
Refusing I hope we will have the opportunity to meet schedule on that day.
on another occasion in the near future. I am I hope we can meet up soon. Good luck with
sure that the meeting will be a great success. the meeting!

Writing Styles
Formal / Neutral Informal
Thank you for your email received 12 Feb.
With regard/reference to ... Thanks for the email.
I would be grateful if you could ... Re ...
We regret to advise you that ... Please could you ...
Please accept our apologies for ... I’m sorry to tell you that ...
I was wondering if you could ... I’m sorry for ...
We note that you have not ... Could you ...?
Example We would like to remind you that ... You haven’t ...
phrases It is necessary for me to ... Don’t forget that ...
It is possible that I will ... I need to ...
Would you like me to ...? I might ...
However, .../In addition, ... / Therefore, ... Shall I ...?
If you require any further information, But, ... / Also, ... / So, ...
please do not hesitate to contact me. If you’d like more details, let me know.
I look forward to meeting you next week See you next week.

Assistance / due to / enquire / inform /


information / obtain / occupation / possess Help / because of / ask / tell / facts / get /
Latin / Anglo-
/ provide / repair / request / requirements job / have / give / fix / ask for / needs /
Saxon origin
/ verify check (prove)

Direct / Indirect
Design and preparation by Eng. \ Mustafa Gouda
Direct Indirect: polite / diplomatic
Can you ...? Could you ...?
Requests
Please could you ... I was wondering if you could ...
Asking for Can I ...? Is it all right if ...?
permission Could I ...? I wonder if I could ...?
Offering help Can I ...? / Shall I ...? Would you like me to ..? / Do you need any help with ...?
Making a What about ... (+ing)? Why don’t we ...?
suggestion Shall we ...? Perhaps we should ...?
I’m afraid there is a small problem.
It seems there is a slight problem.
There is a problem. That might be quite expensive.
That will be very expensive. Won’t that be a bit expensive?
Softening a
We can’t do that . I’m not sure we can do that.
strong
That gives us very little time. Actually, that doesn’t give us much time. Wouldn’t it be
comment
It will be better to ask Heidi. better to ask Heidi?
I disagree. I can see what you’re saying, but ...
Don’t you think that ...?
To be honest, I think it might be better to ...

Request for information (customer)


Saying how you We met last Thursday on your stand at the Munich Trade Fair.
got the contact I am emailing you off your website, which I found through Google.
Giving reason for We are a manufacturer / supplier / provider of ... We are interested in ...
writing We are a Turkish company exporting to the EU, and we need ...
We would be grateful for some information about ...
General requests
Please send us information about your product range and prices.
In particular, we would like to know ...
Specific requests Please send full details of your prices, discounts, terms of payment and delivery times.
Could you also say whether there is any minimum order.
An early reply would be greatly appreciated.
Close I look forward to an early reply, and am sure that there is a market for your products
here in Hungary.

Giving information (supplier)


Thanks Thank you for your email of 4 June inquiring about ...
We can quote a price of ... CIF / FOB Istanbul.
We can delivery by ... (date) / within ... (period of time)
The goods will be shipped 3 days from receipt of a firm order.
Giving factual We can offer a discount of ... on orders over ... .
information We require payment by bank transfer / letter of credit.
Our normal procedure is to ...
Our normal terms for first-time customers are ...
We can supply the items you require directly from stock.
Saying what you are I am attaching a document that gives full details of ...
attaching I am attaching our current catalogue and price list as a pdf file.
Highlighting one or two You will see that ...
key points You will note that our line of .... is on special offer.
You will also note that ... Our experience in this field includes ...
Answering specific We dispatch the goods within 24 hours of a firm order, and for first-time
questions customers our minimum order is $ 1,000.
I am afraid that model is no longer available. However, ...
We feel sure that ... May I suggest that I call you at your convenience to
discuss the matter further?
Close
If you need any further information, please do not hesitate to contact me. My
direct line is...

Design and preparation by Eng. \ Mustafa Gouda


Making an order (customer)
Thank you for your recent email, and we accept your quotation. Our completed order form is
Open
attached, and we give full bank details below.
Close Please acknowledge receipt of this order.

Confirming an order (supplier)


Your order has been received.
We can confirm that your goods have been shipped.
You can track shipping details on our website.
Open
Due to exceptional demand these items are temporarily out of stock. We hope to be able to ship
your order within ... days and will keep you fully informed. We apologize for any inconvenience
this may cause.
We are confident that the goods will meet your expectations. Should there be any questions,
Close
please do not hesitate to contact me, either by email or phone

Asking for payment (supplier)


We are writing concerning a payment of $12,600 for invoice number KJ678 which is now
First reminder –
overdue. A copy of the invoice is attached.
open
According to our records, the sum of $4,500 is still outstanding on your account
Please send a bank transfer to settle the account, or an explanation of why the balance
First reminder – is still outstanding. If you have already dealt with this matter, please disregard this
action email.
We could appreciate your cooperation in resolving this matter as soon as possible.
On (date) I wrote to you regarding your company’s unpaid account , amounting to
$4,500. May we please remind you that this amount is still outstanding.
Second/third
I wish to draw your attention to my previous emails of (dates) about the overdue
reminder – open
payment on your account. We are very concerned that the matter has not yet receive
your attention.
We need a bank transfer in full settlement without further delay.
Clearly, this situation cannot be allowed to continue, and we must ask you to take
Second/third
immediate action to settle your account.
reminder – action
If you have any queries on this mater, please do not hesitate to contact me. Thank you
for your cooperation.
Following my emails of (dates) I must inform you that we have still not received
payment for the outstanding sum of $4,500.
Final demand –
I wrote to you on (dates) regarding the balance of $12,600 on your account. I attach
open
copies of both emails. This sum is now two months overdue. We are very concerned
that the matter has not yet received your attention.
Unless we receive payment within seven days, we shall have no alternative but to take
Final demand –
legal action to recover the money.
action
In the meantime, your existing credit facilities have been suspended.

Design and preparation by Eng. \ Mustafa Gouda


Complaints and Apologies
Complaining (customer)
I am writing ...
in connection with my order FS690 which arrived this morning.
to complain about the quality of a product I bought from your website.
Open
to complain about the poor service we received from your company.
to draw your attention to the negative attitude of some people in your customer services
section
Our order dated 16 September clearly stated that we wanted 1,000 items, however you ...
The goods were faulty / damaged / in poor condition.
There seems to be an error in the invoice /a misunderstanding.
The equipment I ordered has still not been delivered, despite my phone call you last week to
Complaint
say that it is needed urgently.
The product I received was well below the standard expected.
To make matters worse, when I called your company staff ...

Please replace the faulty goods as soon as possible.


We must insist on an immediate replacement / full refund.
Request
Unless I receive the goods by the end of this week, I will have no choice but to cancel my
for action
order.

I hope that you will deal with this matter promptly as it is causing me considerable
Close inconvenience.

Apologizing (supplier)
Open I am writing in relation to your recent complaint.
I was very concerned to learn about ... Please accept my sincere apologies.
Apologizing I would like to apologize for the inconvenience you have suffered.

We appreciate that this has caused you considerable inconvenience, but we cannot accept
Denying
any responsibility in this matter.
responsibility
Can you leave it with me? I’ll look into the matter and get back to you tomorrow.
I have looked into the matter and ...
I have spoken to the staff involved, and ...
Promising
We will send replacement items / give you a refund immediately.
action
I can assure you that this will not happen again.
We’re having a temporary problem with ... . We’re doing everything we can to sort it out.

To compensate for the inconvenience, we would like to offer you ...


Compensation
Thank you for bringing this matter to my attention. Please accept my assurance that it
will not happen again.
Once again, I hope you will accept my apologies for the inconvenience caused.
Close
I very much hope you will continue to use our services in the future.
If you have any further queries, please do not hesitate to contact me on my direct line...

Design and preparation by Eng. \ Mustafa Gouda


Personal
Being Friendly
You heard something, but you are not sure
It seems that ... Apparently, ...
Something is true, but surprising
Actually, ... In fact, ...
Something is obvious or already known
Obviously, ... Of course ...
Good/ bad fortune
Unfortunately, ... Luckily, ...
Saying what you really think
To be honest, ... Frankly, ...
Going back to a topic
Well, ... So, ... Anyway, ...
Changing the topic
Anyway, ... So, ... By the way, ...
Summarizing with the most important
point Anyway, ... Basically, ...

Asking for advice


Formal/Neutral Informal
I’d like your advice about a
Open problem I have I’ve got a bit of a problem.

I was wondering if you had any


Asking for ideas about ...? Do you have any ideas about ...?
advice What would you advise me to do? What should I do?

Please write back when you have


the time and let me know what
Close Please email me when you get the chance.
you think.

Giving advice
Formal/Neutral Informal
I was sorry to hear about your current
I’m sorry you’re having such a hard time at the
Open difficulties.
moment.
I think it might be a good idea to ...
Giving I think you should ...
Have you thought of ... (+ing)?
advice What about ... (+ing)?
This would mean that ...
Result That way, ...
I think this option would be preferable
Options to ... (+ing) I think it’s better than ... (+ing)

Close
I hope I have been of some help. I hope I’ve helped a bit.

Design and preparation by Eng. \ Mustafa Gouda


Suggestions
I think we should / I suggest that we / Let’s go to ...
Shall we / Perhaps we could/Why don’t we go to ...?
Making a suggestion
I suggest... /How about going to ...?

It’s a great idea!


I think your idea would work really well.
Accepting
It might be worth trying.

I’m not so sure about your idea.


It sounds like a good idea, but I don’t think it would work in practice.
Rejecting
It sounds like a good idea, but I can see one or two problems.

Special situations
Just a quick note to say many thanks for ...
Thanks I really appreciate everything that you have done.

Good luck with ...I would like to take this opportunity to wish you every success
Good luck in the future.

Many congratulations on your promotion / new job.


I was delighted to hear the news about ...
Congratulations
Well done!

Please give my best wishes/regards to ...


Best wishes
I was so sorry to hear about ...
I was really sorry to hear you’re not well ...Hope you feel better soon.
Bad news
If there’s anything I can do to help, let me know.

Job Application
Greeting Dear Sir/Madam
Reason for With reference to your advertisement on the ... website, I am interested in applying
writing for the post of...
Your
background I am 26 years old and am currently studying for a degree in ... at ... University.
and For the last two months I have been working as a ... at ... .
experience
I am interested in this job because ...
The job itself
I feel that I would be well-suited for this job/have a lot of experience in ...
Referring to I have attached my CV as a Word document. You will notice that I ... as well as ... .
your CV You will also notice that ... .
I would be grateful if you would consider my application.
You will see from my CV that two people can be contacted as references, one is ...
Final
and the other is from ... .
comments
I am available for interview in .../ by phone any weekday afternoon, and you can
email me or telephone me on the number below.
I look forward to hearing from you soon.
Close
Yours faithfully

Design and preparation by Eng. \ Mustafa Gouda


Reports
Report structure
As requested at the Board meeting of 18 April, here is my report.
Introduction / The report will discus / consider / describe / analyze / review ...
Background The report is based on ...
I have divided the report into three sections.
The findings / figures / results / investigations show that ...
Findings It appears that ... . This has led to a situation where ...
The graph/table shows that ...
As can be seen in table 1 / section 2 / figure 3, ...
Signposts As mentioned above, ... / ..., see below.
...and I will discuss this in more detail below /in section 3.2.
Conclusion / I (would like to) suggest /recommend that ...
Recommendations My specific recommendations are as follows.
Please have a look at the report and let me have your comments.
Closing comments
Please feel free to contact me if you have any questions.

Linking words
Sequence Firstly / secondly / finally
Talking generally In general / usually / on the whole
Contrast However / nevertheless / on the other hand
Adding another point In addition / moreover / on another point
Examples For example / for instance / e.g.
Alternatives Either ... or ... / alternatively / instead of ...
Real (surprising) situation In fact, / actually, / as a matter of fact
Something is obvious Clearly / obviously / of course
Most important point Especially / above all / in particular
Rephrasing In other words / that is to say / i.e.
Result/consequence As a result / therefore / for this reason
New topic In relation to / regarding / with reference to

Careful, balanced style


In general ..., however ...
Giving both sides of an argument
On the whole ..., but ...
Many / some ...
Making a statement less general
Usually / typically / often ...
It is possible / probable that ...
Making a statement less certain It seems / appears that ...
... tends to be...
Substantially / considerably / much (+ comparative adjective)
Making a comparison less strong Significantly / relatively (+ comparative adjective)
Marginally / slightly (+ comparative adjective)
On balance, ...
Concluding
Taking all the above points into consideration, ...

Design and preparation by Eng. \ Mustafa Gouda


Coding Interview in
Java
Program Creek

May 1st, 2016

1 of
1 of 246
288
Contents

1 Rotate Array in Java 13

2 Evaluate Reverse Polish Notation 17

3 Isomorphic Strings 21

4 Word Ladder 23

5 Word Ladder II 25

6 Median of Two Sorted Arrays 29

7 Kth Largest Element in an Array 31

8 Wildcard Matching 33

9 Regular Expression Matching in Java 35

10 Merge Intervals 39

11 Insert Interval 41

12 Two Sum 43

13 Two Sum II Input array is sorted 45

14 Two Sum III Data structure design 47

15 3Sum 49

16 4Sum 53

17 3Sum Closest 55

18 String to Integer (atoi) 57

19 Merge Sorted Array 59

20 Valid Parentheses 61

2 | 531

2 of
2 of 246
288
Contents

21 Longest Valid Parentheses 63

22 Implement strStr() 65

23 Minimum Size Subarray Sum 69

24 Search Insert Position 73

25 Longest Consecutive Sequence 75

26 Valid Palindrome 77

27 ZigZag Conversion 81

28 Add Binary 83

29 Length of Last Word 85

30 Triangle 87

31 Contains Duplicate 89

32 Contains Duplicate II 91

33 Contains Duplicate III 93

34 Remove Duplicates from Sorted Array 95

35 Remove Duplicates from Sorted Array II 99

36 Longest Substring Without Repeating Characters 103

37 Longest Substring Which Contains 2 Unique Characters 105

38 Substring with Concatenation of All Words 109

39 Minimum Window Substring 111

40 Reverse Words in a String 113

41 Find Minimum in Rotated Sorted Array 115

42 Find Minimum in Rotated Sorted Array II 117

43 Search in Rotated Sorted Array 119

44 Search in Rotated Sorted Array II 121

45 Min Stack 123

Program Creek 3 | 531

3 of
3 of 246
288
Contents

46 Majority Element 125

47 Majority Element II 127

48 Remove Element 129

49 Largest Rectangle in Histogram 131

50 Longest Common Prefix 133

51 Largest Number 135

52 Simplify Path 137

53 Compare Version Numbers 139

54 Gas Station 141

55 Pascal’s Triangle 143

56 Pascal’s Triangle II 145

57 Container With Most Water 147

58 Candy 149

59 Trapping Rain Water 151

60 Count and Say 153

61 Search for a Range 155

62 Basic Calculator 157

63 Group Anagrams 159

64 Shortest Palindrome 161

65 Rectangle Area 163

66 Summary Ranges 165

67 Increasing Triplet Subsequence 167

68 Get Target Number Using Number List and Arithmetic Operations 169

69 Reverse Vowels of a String 171

70 Flip Game 173

4 | 531 Program Creek

4 of
4 of 246
288
Contents

71 Flip Game II 175

72 Move Zeroes 177

73 Valid Anagram 179

74 Group Shifted Strings 181

75 Top K Frequent Elements 183

76 Find Peak Element 185

77 Word Pattern 187

78 Set Matrix Zeroes 189

79 Spiral Matrix 193

80 Spiral Matrix II 197

81 Search a 2D Matrix 199

82 Search a 2D Matrix II 201

83 Rotate Image 205

84 Valid Sudoku 207

85 Minimum Path Sum 209

86 Unique Paths 211

87 Unique Paths II 213

88 Number of Islands 215

89 Number of Islands II 217

90 Surrounded Regions 219

91 Maximal Rectangle 223

92 Maximal Square 225

93 Word Search 227

94 Word Search II 229

95 Integer Break 233

Program Creek 5 | 531

5 of
5 of 246
288
Contents

96 Range Sum Query 2D Immutable 235

97 Longest Increasing Path in a Matrix 237

98 Implement a Stack Using an Array in Java 239

99 Add Two Numbers 243

100 Reorder List 245

101 Linked List Cycle 251

102 Copy List with Random Pointer 253

103 Merge Two Sorted Lists 257

104 Odd Even Linked List 259

105 Remove Duplicates from Sorted List 261

106 Remove Duplicates from Sorted List II 263

107 Partition List 265

108 LRU Cache 267

109 Intersection of Two Linked Lists 271

110 Remove Linked List Elements 273

111 Swap Nodes in Pairs 275

112 Reverse Linked List 277

113 Reverse Linked List II 279

114 Remove Nth Node From End of List 281

115 Implement Stack using Queues 283

116 Implement Queue using Stacks 285

117 Palindrome Linked List 287

118 Implement a Queue using an Array in Java 289

119 Delete Node in a Linked List 291

120 Moving Average from Data Stream 293

6 | 531 Program Creek

6 of
6 of 246
288
1 Rotate Array in Java

You may have been using Java for a while. Do you think a simple Java array question
can be a challenge? Let’s use the following problem to test.
Problem: Rotate an array of n elements to the right by k steps. For example, with n
= 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different
ways do you know to solve this problem?

1.1 Solution 1 - Intermediate Array

In a straightforward way, we can create a new array and then copy elements to the
new array. Then change the original array by using System.arraycopy().
public void rotate(int[] nums, int k) {
if(k > nums.length)
k=k%nums.length;

int[] result = new int[nums.length];

for(int i=0; i < k; i++){


result[i] = nums[nums.length-k+i];
}

int j=0;
for(int i=k; i<nums.length; i++){
result[i] = nums[j];
j++;
}

System.arraycopy( result, 0, nums, 0, nums.length );


}

Space is O(n) and time is O(n). You can check out the difference between Sys-
tem.arraycopy() and Arrays.copyOf().

1.2 Solution 2 - Bubble Rotate

Can we do this in O(1) space?


This solution is like a bubble sort.
public static void rotate(int[] arr, int order) {
if (arr == null || order < 0) {

13 | 531

7 of
7 of 246
288
1 Rotate Array in Java

throw new IllegalArgumentException("Illegal argument!");


}

for (int i = 0; i < order; i++) {


for (int j = arr.length - 1; j > 0; j--) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}

However, the time is O(n*k).


Here is an example (length=7, order=3):
i=0
0 1 2 3 4 5 6
0 1 2 3 4 6 5
...
6 0 1 2 3 4 5
i=1
6 0 1 2 3 5 4
...
5 6 0 1 2 3 4
i=2
5 6 0 1 2 4 3
...
4 5 6 0 1 2 3

1.3 Solution 3 - Reversal

Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given 1,2,3,4,5,6 and order 2. The basic idea is:
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4

public static void rotate(int[] arr, int order) {


if (arr == null || arr.length==0 || order < 0) {
throw new IllegalArgumentException("Illegal argument!");
}

if(order > arr.length){


order = order %arr.length;
}

14 | 531 Program Creek

8 of
8 of 246
288
1 Rotate Array in Java

//length of first part


int a = arr.length - order;

reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);

public static void reverse(int[] arr, int left, int right){


if(arr == null || arr.length == 1)
return;

while(left < right){


int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}

Program Creek 15 | 531

9 of
9 of 246
288
2 Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid op-
erators are +, -, *, /. Each operand may be an integer or another expression. For
example:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

2.1 Naive Approach

This problem can be solved by using a stack. We can loop through each element in the
given array. When it is a number, push it to the stack. When it is an operator, pop two
numbers from the stack, do the calculation, and push back the result.

The following is the code. However, this code contains compilation errors in leet-
code. Why?
public class Test {

public static void main(String[] args) throws IOException {


String[] tokens = new String[] { "2", "1", "+", "3", "*" };
System.out.println(evalRPN(tokens));
}

17 | 531

11 of
10 of 246
288
2 Evaluate Reverse Polish Notation

public static int evalRPN(String[] tokens) {


int returnValue = 0;
String operators = "+-*/";

Stack<String> stack = new Stack<String>();

for (String t : tokens) {


if (!operators.contains(t)) { //push to stack if it is a number
stack.push(t);
} else {//pop numbers from stack if it is an operator
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch (t) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}

returnValue = Integer.valueOf(stack.pop());

return returnValue;
}
}

The problem is that switch string statement is only available from JDK 1.7. Leetcode
apparently use a JDK version below 1.7.

2.2 Accepted Solution

If you want to use switch statement, you can convert the above by using the following
code which use the index of a string "+-*/".
public class Solution {
public int evalRPN(String[] tokens) {

int returnValue = 0;

18 | 531 Program Creek

12 of
11 of 246
288
2 Evaluate Reverse Polish Notation

String operators = "+-*/";

Stack<String> stack = new Stack<String>();

for(String t : tokens){
if(!operators.contains(t)){
stack.push(t);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}
}

returnValue = Integer.valueOf(stack.pop());

return returnValue;

}
}

Program Creek 19 | 531

13 of
12 of 246
288
3 Isomorphic Strings

Given two strings s and t, determine if they are isomorphic. Two strings are isomor-
phic if the characters in s can be replaced to get t.
For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.

3.1 Analysis

We need to define a method which accepts a map & a value, and returns the value’s
key in the map.

3.2 Java Solution

public boolean isIsomorphic(String s, String t) {


if(s==null || t==null)
return false;

if(s.length() != t.length())
return false;

if(s.length()==0 && t.length()==0)


return true;

HashMap<Character, Character> map = new HashMap<Character,Character>();


for(int i=0; i<s.length(); i++){
char c1 = s.charAt(i);
char c2 = t.charAt(i);

Character c = getKey(map, c2);


if(c != null && c!=c1){
return false;
}else if(map.containsKey(c1)){
if(c2 != map.get(c1))
return false;
}else{
map.put(c1,c2);
}
}

return true;
}

21 | 531

15 of
13 of 246
288
3 Isomorphic Strings

// a method for getting key of a target value


public Character getKey(HashMap<Character,Character> map, Character target){
for (Map.Entry<Character,Character> entry : map.entrySet()) {
if (entry.getValue().equals(target)) {
return entry.getKey();
}
}

return null;
}

22 | 531 Program Creek

16 of
14 of 246
288
4 Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transfor-
mation sequence from start to end, such that only one letter can be changed at a time
and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

One shortest transformation is "hit" ->"hot" ->"dot" ->"dog" ->"cog", the program
should return its length 5.

4.1 Analysis

UPDATED on 06/07/2015.
So we quickly realize that this is a search problem, and breath-first search guarantees
the optimal solution.

4.2 Java Solution

class WordNode{
String word;
int numSteps;

public WordNode(String word, int numSteps){


this.word = word;
this.numSteps = numSteps;
}
}

23 | 531

17 of
15 of 246
288
4 Word Ladder

public class Solution {


public int ladderLength(String beginWord, String endWord, Set<String>
wordDict) {
LinkedList<WordNode> queue = new LinkedList<WordNode>();
queue.add(new WordNode(beginWord, 1));

wordDict.add(endWord);

while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;

if(word.equals(endWord)){
return top.numSteps;
}

char[] arr = word.toCharArray();


for(int i=0; i<arr.length; i++){
for(char c=’a’; c<=’z’; c++){
char temp = arr[i];
if(arr[i]!=c){
arr[i]=c;
}

String newWord = new String(arr);


if(wordDict.contains(newWord)){
queue.add(new WordNode(newWord, top.numSteps+1));
wordDict.remove(newWord);
}

arr[i]=temp;
}
}
}

return 0;
}
}

24 | 531 Program Creek

18 of
16 of 246
288
5 Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation
sequence(s) from start to end, such that: 1) Only one letter can be changed at a time,
2) Each intermediate word must exist in the dictionary.
For example, given: start = "hit", end = "cog", and dict = ["hot","dot","dog","lot","log"],
return:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

5.1 Analysis

This is an extension of Word Ladder.


The idea is the same. To track the actual ladder, we need to add a pointer that points
to the previous node in the WordNode class.
In addition, the used word can not directly removed from the dictionary. The used
word is only removed when steps change.

5.2 Java Solution

class WordNode{
String word;
int numSteps;
WordNode pre;

public WordNode(String word, int numSteps, WordNode pre){


this.word = word;
this.numSteps = numSteps;
this.pre = pre;
}
}

public class Solution {


public List<List<String>> findLadders(String start, String end,
Set<String> dict) {
List<List<String>> result = new ArrayList<List<String>>();

25 | 531

19 of
17 of 246
288
5 Word Ladder II

LinkedList<WordNode> queue = new LinkedList<WordNode>();


queue.add(new WordNode(start, 1, null));

dict.add(end);

int minStep = 0;

HashSet<String> visited = new HashSet<String>();


HashSet<String> unvisited = new HashSet<String>();
unvisited.addAll(dict);

int preNumSteps = 0;

while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;
int currNumSteps = top.numSteps;

if(word.equals(end)){
if(minStep == 0){
minStep = top.numSteps;
}

if(top.numSteps == minStep && minStep !=0){


//nothing
ArrayList<String> t = new ArrayList<String>();
t.add(top.word);
while(top.pre !=null){
t.add(0, top.pre.word);
top = top.pre;
}
result.add(t);
continue;
}

if(preNumSteps < currNumSteps){


unvisited.removeAll(visited);
}

preNumSteps = currNumSteps;

char[] arr = word.toCharArray();


for(int i=0; i<arr.length; i++){
for(char c=’a’; c<=’z’; c++){
char temp = arr[i];
if(arr[i]!=c){
arr[i]=c;
}

26 | 531 Program Creek

20 of
18 of 246
288
5 Word Ladder II

String newWord = new String(arr);


if(unvisited.contains(newWord)){
queue.add(new WordNode(newWord, top.numSteps+1, top));
visited.add(newWord);
}

arr[i]=temp;
}
}

return result;
}
}

Program Creek 27 | 531

21 of
19 of 246
288
6 Median of Two Sorted Arrays

There are two sorted arrays A and B of size m and n respectively. Find the median of the
two sorted arrays. The overall run time complexity should be O(log (m+n)).

6.1 Java Solution 1

If we see log(n), we should think about using binary something.


This problem can be converted to the problem of finding kth element, k is (A’s
length + B’ Length)/2.
If any of the two arrays is empty, then the kth element is the non-empty array’s kth
element. If k == 0, the kth element is the first element of A or B.
For normal cases(all other cases), we need to move the pointer at the pace of half of
an array length to get log(n) time.
public static double findMedianSortedArrays(int A[], int B[]) {
int m = A.length;
int n = B.length;

if ((m + n) % 2 != 0) // odd
return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1);
else { // even
return (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1)
+ findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) * 0.5;
}
}

public static int findKth(int A[], int B[], int k,


int aStart, int aEnd, int bStart, int bEnd) {

int aLen = aEnd - aStart + 1;


int bLen = bEnd - bStart + 1;

// Handle special cases


if (aLen == 0)
return B[bStart + k];
if (bLen == 0)
return A[aStart + k];
if (k == 0)
return A[aStart] < B[bStart] ? A[aStart] : B[bStart];

int aMid = aLen * k / (aLen + bLen); // a’s middle count


int bMid = k - aMid - 1; // b’s middle count

29 | 531

23 of
20 of 246
288
6 Median of Two Sorted Arrays

// make aMid and bMid to be array index


aMid = aMid + aStart;
bMid = bMid + bStart;

if (A[aMid] > B[bMid]) {


k = k - (bMid - bStart + 1);
aEnd = aMid;
bStart = bMid + 1;
} else {
k = k - (aMid - aStart + 1);
bEnd = bMid;
aStart = aMid + 1;
}

return findKth(A, B, k, aStart, aEnd, bStart, bEnd);


}

6.2 Java Solution 2

Solution 1 is a general solution to find the kth element. We can also come up with a
simpler solution which only finds the median of two sorted arrays for this particular
problem. Thanks to Gunner86. The description of the algorithm is awesome!
1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[]
respectively.
2) If m1 and m2 both are equal then we are done, and return m1 (or m2)
3) If m1 is greater than m2, then median is present in one of the below two
subarrays.
a) From first element of ar1 to m1 (ar1[0...|_n/2_|])
b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one of the below two
subarrays.
a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])
b) From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays becomes 2.
6) If size of the two arrays is 2 then use below formula to get the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2

30 | 531 Program Creek

24 of
21 of 246
288
7 Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element
in the sorted order, not the kth distinct element.
For example, given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.

7.1 Java Solution 1 - Sorting

public int findKthLargest(int[] nums, int k) {


Arrays.sort(nums);
return nums[nums.length-k];
}

Time is O(nlog(n))

7.2 Java Solution 2 - Quick Sort

This problem can also be solve by using the quickselect approach, which is similar to
quicksort.
public int findKthLargest(int[] nums, int k) {
if (k < 1 || nums == null) {
return 0;
}

return getKth(nums.length - k +1, nums, 0, nums.length - 1);


}

public int getKth(int k, int[] nums, int start, int end) {

int pivot = nums[end];

int left = start;


int right = end;

while (true) {

while (nums[left] < pivot && left < right) {


left++;
}

31 | 531

25 of
22 of 246
288
7 Kth Largest Element in an Array

while (nums[right] >= pivot && right > left) {


right--;
}

if (left == right) {
break;
}

swap(nums, left, right);


}

swap(nums, left, end);

if (k == left + 1) {
return pivot;
} else if (k < left + 1) {
return getKth(k, nums, start, left - 1);
} else {
return getKth(k, nums, left + 1, end);
}
}

public void swap(int[] nums, int n1, int n2) {


int tmp = nums[n1];
nums[n1] = nums[n2];
nums[n2] = tmp;
}

Average case time is O(n), worst case time is O(n2̂).

7.3 Java Solution 3 - Heap

We can use a min heap to solve this problem. The heap stores the top k elements.
Whenever the size is greater than k, delete the min. Time complexity is O(nlog(k)).
Space complexity is O(k) for storing the top k numbers.
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> q = new PriorityQueue<Integer>(k);
for(int i: nums){
q.offer(i);

if(q.size()>k){
q.poll();
}
}

return q.peek();
}

32 | 531 Program Creek

26 of
23 of 246
288
8 Wildcard Matching

Implement wildcard pattern matching with support for ’?’ and ’*’.

8.1 Java Solution

To understand this solution, you can use s="aab" and p="*ab".


public boolean isMatch(String s, String p) {
int i = 0;
int j = 0;
int starIndex = -1;
int iIndex = -1;

while (i < s.length()) {


if (j < p.length() && (p.charAt(j) == ’?’ || p.charAt(j) == s.charAt(i)))
{
++i;
++j;
} else if (j < p.length() && p.charAt(j) == ’*’) {
starIndex = j;
iIndex = i;
j++;
} else if (starIndex != -1) {
j = starIndex + 1;
i = iIndex+1;
iIndex++;
} else {
return false;
}
}

while (j < p.length() && p.charAt(j) == ’*’) {


++j;
}

return j == p.length();
}

33 | 531

27 of
24 of 246
288
9 Regular Expression Matching in Java

Implement regular expression matching with support for ’.’ and ’*’.
’.’ Matches any single character. ’*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be: bool isMatch(const char *s, const char *p)
Some examples: isMatch("aa","a") return false isMatch("aa","aa") return true isMatch("aaa","aa")
return false isMatch("aa", "a*") return true isMatch("aa", ".*") return true isMatch("ab",
".*") return true isMatch("aab", "c*a*b") return true

9.1 Analysis

First of all, this is one of the most difficulty problems. It is hard to think through all
different cases. The problem should be simplified to handle 2 basic cases:

• the second char of pattern is "*"


• the second char of pattern is not "*"

For the 1st case, if the first char of pattern is not ".", the first char of pattern and
string should be the same. Then continue to match the remaining part.
For the 2nd case, if the first char of pattern is "." or first char of pattern == the first i
char of string, continue to match the remaining part.

9.2 Java Solution 1 (Short)

The following Java solution is accepted.


public class Solution {
public boolean isMatch(String s, String p) {

if(p.length() == 0)
return s.length() == 0;

//p’s length 1 is special case


if(p.length() == 1 || p.charAt(1) != ’*’){
if(s.length() < 1 || (p.charAt(0) != ’.’ && s.charAt(0) !=
p.charAt(0)))
return false;
return isMatch(s.substring(1), p.substring(1));

}else{

35 | 531

29 of
25 of 246
288
9 Regular Expression Matching in Java

int len = s.length();

int i = -1;
while(i<len && (i < 0 || p.charAt(0) == ’.’ || p.charAt(0) ==
s.charAt(i))){
if(isMatch(s.substring(i+1), p.substring(2)))
return true;
i++;
}
return false;
}
}
}

9.3 Java Solution 2 (More Readable)

public boolean isMatch(String s, String p) {


// base case
if (p.length() == 0) {
return s.length() == 0;
}

// special case
if (p.length() == 1) {

// if the length of s is 0, return false


if (s.length() < 1) {
return false;
}

//if the first does not match, return false


else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != ’.’)) {
return false;
}

// otherwise, compare the rest of the string of s and p.


else {
return isMatch(s.substring(1), p.substring(1));
}
}

// case 1: when the second char of p is not ’*’


if (p.charAt(1) != ’*’) {
if (s.length() < 1) {
return false;
}
if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != ’.’)) {

36 | 531 Program Creek

30 of
26 of 246
288
9 Regular Expression Matching in Java

return false;
} else {
return isMatch(s.substring(1), p.substring(1));
}
}

// case 2: when the second char of p is ’*’, complex case.


else {
//case 2.1: a char & ’*’ can stand for 0 element
if (isMatch(s, p.substring(2))) {
return true;
}

//case 2.2: a char & ’*’ can stand for 1 or more preceding element,
//so try every sub string
int i = 0;
while (i<s.length() && (s.charAt(i)==p.charAt(0) || p.charAt(0)==’.’)){
if (isMatch(s.substring(i + 1), p.substring(2))) {
return true;
}
i++;
}
return false;
}
}

Program Creek 37 | 531

31 of
27 of 246
288
10 Merge Intervals

Problem:
Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

10.1 Thoughts of This Problem

The key to solve this problem is defining a Comparator first to sort the arraylist of
Intevals. And then merge some intervals.
The take-away message from this problem is utilizing the advantage of sorted list/ar-
ray.

10.2 Java Solution

class Interval {
int start;
int end;

Interval() {
start = 0;
end = 0;
}

Interval(int s, int e) {
start = s;
end = e;
}
}

public class Solution {


public ArrayList<Interval> merge(ArrayList<Interval> intervals) {

if (intervals == null || intervals.size() <= 1)


return intervals;

// sort intervals by using self-defined Comparator

39 | 531

33 of
28 of 246
288
10 Merge Intervals

Collections.sort(intervals, new IntervalComparator());

ArrayList<Interval> result = new ArrayList<Interval>();

Interval prev = intervals.get(0);


for (int i = 1; i < intervals.size(); i++) {
Interval curr = intervals.get(i);

if (prev.end >= curr.start) {


// merged case
Interval merged = new Interval(prev.start, Math.max(prev.end,
curr.end));
prev = merged;
} else {
result.add(prev);
prev = curr;
}
}

result.add(prev);

return result;
}
}

class IntervalComparator implements Comparator<Interval> {


public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
}

40 | 531 Program Creek

34 of
29 of 246
288
11 Insert Interval

Problem:
Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals
(merge if necessary).
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as
[1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

11.1 Thoughts of This Problem

Quickly summarize 3 cases. Whenever there is intersection, created a new interval.

11.2 Java Solution

41 | 531

35 of
30 of 246
288
11 Insert Interval

/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval
newInterval) {

ArrayList<Interval> result = new ArrayList<Interval>();

for(Interval interval: intervals){


if(interval.end < newInterval.start){
result.add(interval);
}else if(interval.start > newInterval.end){
result.add(newInterval);
newInterval = interval;
}else if(interval.end >= newInterval.start || interval.start <=
newInterval.end){
newInterval = new Interval(Math.min(interval.start,
newInterval.start), Math.max(newInterval.end, interval.end));
}
}

result.add(newInterval);

return result;
}
}

42 | 531 Program Creek

36 of
31 of 246
288
12 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target
number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2. Please note that your returned
answers (both index1 and index2) are not zero-based.
For example:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

12.1 Naive Approach

This problem is pretty straightforward. We can simply examine every possible pair of
numbers in this integer array.
Time complexity in worst case: O(n2̂).
public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}

Can we do better?

12.2 Better Solution

Use HashMap to store the target value.


public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];

43 | 531

37 of
32 of 246
288
12 Two Sum

for (int i = 0; i < numbers.length; i++) {


if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index+1 ;
result[1] = i+1;
break;
} else {
map.put(target - numbers[i], i);
}
}

return result;
}
}

Time complexity depends on the put and get operations of HashMap which is nor-
mally O(1).
Time complexity of this solution is O(n).

44 | 531 Program Creek

38 of
33 of 246
288
13 Two Sum II Input array is sorted

This problem is similar to Two Sum.


To solve this problem, we can use two points to scan the array from both sides. See
Java solution below:
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == 0)
return null;

int i = 0;
int j = numbers.length - 1;

while (i < j) {
int x = numbers[i] + numbers[j];
if (x < target) {
++i;
} else if (x > target) {
j--;
} else {
return new int[] { i + 1, j + 1 };
}
}

return null;
}

45 | 531

39 of
34 of 246
288
14 Two Sum III Data structure design

Design and implement a TwoSum class. It should support the following operations:
add and find.
add - Add the number to an internal data structure. find - Find if there exists any
pair of numbers which sum is equal to the value.
For example,
add(1);
add(3);
add(5);
find(4) -> true
find(7) -> false

14.1 Java Solution

Since the desired class need add and get operations, HashMap is a good option for
this purpose.
public class TwoSum {
private HashMap<Integer, Integer> elements = new HashMap<Integer,
Integer>();

public void add(int number) {


if (elements.containsKey(number)) {
elements.put(number, elements.get(number) + 1);
} else {
elements.put(number, 1);
}
}

public boolean find(int value) {


for (Integer i : elements.keySet()) {
int target = value - i;
if (elements.containsKey(target)) {
if (i == target && elements.get(target) < 2) {
continue;
}
return true;
}
}
return false;

47 | 531

41 of
35 of 246
288
14 Two Sum III Data structure design

}
}

48 | 531 Program Creek

42 of
36 of 246
288
15 3Sum

Problem:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:


(-1, 0, 1)
(-1, -1, 2)

15.1 Naive Solution

Naive solution is 3 loops, and this gives time complexity O(n3̂). Apparently this is not
an acceptable solution, but a discussion can start from here.
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
//sort array
Arrays.sort(num);

ArrayList<ArrayList<Integer>> result = new


ArrayList<ArrayList<Integer>>();
ArrayList<Integer> each = new ArrayList<Integer>();
for(int i=0; i<num.length; i++){
if(num[i] > 0) break;

for(int j=i+1; j<num.length; j++){


if(num[i] + num[j] > 0 && num[j] > 0) break;

for(int k=j+1; k<num.length; k++){


if(num[i] + num[j] + num[k] == 0) {

each.add(num[i]);
each.add(num[j]);
each.add(num[k]);
result.add(each);
each.clear();
}

49 | 531

43 of
37 of 246
288
15 3Sum

}
}
}

return result;
}
}

* The solution also does not handle duplicates. Therefore, it is not only time ineffi-
cient, but also incorrect.
Result:
Submission Result: Output Limit Exceeded

15.2 Better Solution

A better solution is using two pointers instead of one. This makes time complexity of
O(n2̂).
To avoid duplicate, we can take advantage of sorted arrays, i.e., move pointers by
>1 to use same element only once.
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

if (num.length < 3)
return result;

// sort array
Arrays.sort(num);

for (int i = 0; i < num.length - 2; i++) {


// //avoid duplicate solutions
if (i == 0 || num[i] > num[i - 1]) {

int negate = -num[i];

int start = i + 1;
int end = num.length - 1;

while (start < end) {


//case 1
if (num[start] + num[end] == negate) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);
temp.add(num[start]);
temp.add(num[end]);

result.add(temp);

50 | 531 Program Creek

44 of
38 of 246
288
15 3Sum

start++;
end--;
//avoid duplicate solutions
while (start < end && num[end] == num[end + 1])
end--;

while (start < end && num[start] == num[start - 1])


start++;
//case 2
} else if (num[start] + num[end] < negate) {
start++;
//case 3
} else {
end--;
}
}

}
}

return result;
}

Program Creek 51 | 531

45 of
39 of 246
288
16 4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c


+ d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤
b ≤ c ≤ d) The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:


(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)

16.1 Thoughts

A typical k-sum problem. Time is N to the power of (k-1).

16.2 Java Solution

public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {


Arrays.sort(num);

HashSet<ArrayList<Integer>> hashSet = new HashSet<ArrayList<Integer>>();


ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

for (int i = 0; i < num.length; i++) {


for (int j = i + 1; j < num.length; j++) {
int k = j + 1;
int l = num.length - 1;

while (k < l) {
int sum = num[i] + num[j] + num[k] + num[l];

if (sum > target) {


l--;
} else if (sum < target) {
k++;
} else if (sum == target) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(num[i]);

53 | 531

47 of
40 of 246
288
16 4Sum

temp.add(num[j]);
temp.add(num[k]);
temp.add(num[l]);

if (!hashSet.contains(temp)) {
hashSet.add(temp);
result.add(temp);
}

k++;
l--;
}
}
}
}

return result;
}

Here is the hashCode method of ArrayList. It makes sure that if all elements of two
lists are the same, then the hash code of the two lists will be the same. Since each
element in the ArrayList is Integer, same integer has same hash code.
int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}

54 | 531 Program Creek

48 of
41 of 246
288
17 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a
given number, target. Return the sum of the three integers. You may assume that each
input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

17.1 Analysis

This problem is similar to 2 Sum. This kind of problem can be solved by using a
similar approach, i.e., two pointers from both left and right.

17.2 Java Solution

public int threeSumClosest(int[] nums, int target) {


int min = Integer.MAX_VALUE;
int result = 0;

Arrays.sort(nums);

for (int i = 0; i < nums.length; i++) {


int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
int diff = Math.abs(sum - target);

if(diff == 0) return sum;

if (diff < min) {


min = diff;
result = sum;
}
if (sum <= target) {
j++;
} else {
k--;
}
}

55 | 531

49 of
42 of 246
288
17 3Sum Closest

return result;
}

Time Complexity is O(n2̂).

56 | 531 Program Creek

50 of
43 of 246
288
18 String to Integer (atoi)

Implement atoi to convert a string to an integer.


Hint: Carefully consider all possible input cases. If you want a challenge, please do
not see below and ask yourself what are the possible input cases.

18.1 Analysis

The following cases should be considered for this problem:


1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max

18.2 Java Solution

public int atoi(String str) {


if (str == null || str.length() < 1)
return 0;

// trim white spaces


str = str.trim();

char flag = ’+’;

// check negative or positive


int i = 0;
if (str.charAt(0) == ’-’) {
flag = ’-’;
i++;
} else if (str.charAt(0) == ’+’) {
i++;
}
// use double to store result
double result = 0;

// calculate value
while (str.length() > i && str.charAt(i) >= ’0’ && str.charAt(i) <= ’9’) {
result = result * 10 + (str.charAt(i) - ’0’);

57 | 531

51 of
44 of 246
288
18 String to Integer (atoi)

i++;
}

if (flag == ’-’)
result = -result;

// handle max and min


if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;

if (result < Integer.MIN_VALUE)


return Integer.MIN_VALUE;

return (int) result;


}

58 | 531 Program Creek

52 of
45 of 246
288
19 Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You may assume that A has enough space to hold additional elements from
B. The number of elements initialized in A and B are m and n respectively.

19.1 Analysis

The key to solve this problem is moving element of A and B backwards. If B has some
elements left after A is done, also need to handle that case.
The takeaway message from this problem is that the loop condition. This kind of
condition is also used for merging two sorted linked list.

19.2 Java Solution 1

public class Solution {


public void merge(int A[], int m, int B[], int n) {

while(m > 0 && n > 0){


if(A[m-1] > B[n-1]){
A[m+n-1] = A[m-1];
m--;
}else{
A[m+n-1] = B[n-1];
n--;
}
}

while(n > 0){


A[m+n-1] = B[n-1];
n--;
}
}
}

19.3 Java Solution 2

The loop condition also can use m+n like the following.

59 | 531

53 of
46 of 246
288
19 Merge Sorted Array

public void merge(int A[], int m, int B[], int n) {


int i = m - 1;
int j = n - 1;
int k = m + n - 1;

while (k >= 0) {
if (j < 0 || (i >= 0 && A[i] > B[j]))
A[k--] = A[i--];
else
A[k--] = B[j--];
}
}

60 | 531 Program Creek

54 of
47 of 246
288
20 Valid Parentheses

Given a string containing just the characters ’(’, ’)’, ’’, ’’, ’[’ and ’]’, determine if the
input string is valid. The brackets must close in the correct order, "()" and "()[]" are all
valid but "(]" and "([)]" are not.

20.1 Analysis

A typical problem which can be solved by using a stack data structure.

20.2 Java Solution

public static boolean isValid(String s) {


HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put(’(’, ’)’);
map.put(’[’, ’]’);
map.put(’{’, ’}’);

Stack<Character> stack = new Stack<Character>();

for (int i = 0; i < s.length(); i++) {


char curr = s.charAt(i);

if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}

return stack.empty();
}

61 | 531

55 of
48 of 246
288
21 Longest Valid Parentheses

Given a string containing just the characters ’(’ and ’)’, find the length of the longest
valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2. An-
other example is ")()())", where the longest valid parentheses substring is "()()", which
has length = 4.

21.1 Analysis

This problem is similar with Valid Parentheses, which can be solved by using a stack.

21.2 Java Solution

public static int longestValidParentheses(String s) {


Stack<int[]> stack = new Stack<int[]>();
int result = 0;

for(int i=0; i<=s.length()-1; i++){


char c = s.charAt(i);
if(c==’(’){
int[] a = {i,0};
stack.push(a);
}else{
if(stack.empty()||stack.peek()[1]==1){
int[] a = {i,1};
stack.push(a);
}else{
stack.pop();
int currentLen=0;
if(stack.empty()){
currentLen = i+1;
}else{
currentLen = i-stack.peek()[0];
}
result = Math.max(result, currentLen);
}
}
}

return result;

63 | 531

57 of
49 of 246
288
21 Longest Valid Parentheses

64 | 531 Program Creek

58 of
50 of 246
288
22 Implement strStr()

Problem:
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1
if needle is not part of haystack.

22.1 Java Solution 1 - Naive

public int strStr(String haystack, String needle) {


if(haystack==null || needle==null)
return 0;

if(needle.length() == 0)
return 0;

for(int i=0; i<haystack.length(); i++){


if(i + needle.length() > haystack.length())
return -1;

int m = i;
for(int j=0; j<needle.length(); j++){
if(needle.charAt(j)==haystack.charAt(m)){
if(j==needle.length()-1)
return i;
m++;
}else{
break;
}

}
}

return -1;
}

22.2 Java Solution 2 - KMP

Check out this article to understand KMP algorithm.


public int strStr(String haystack, String needle) {
if(haystack==null || needle==null)

65 | 531

59 of
51 of 246
288
22 Implement strStr()

return 0;

int h = haystack.length();
int n = needle.length();

if (n > h)
return -1;
if (n == 0)
return 0;

int[] next = getNext(needle);


int i = 0;

while (i <= h - n) {
int success = 1;
for (int j = 0; j < n; j++) {
if (needle.charAt(0) != haystack.charAt(i)) {
success = 0;
i++;
break;
} else if (needle.charAt(j) != haystack.charAt(i + j)) {
success = 0;
i = i + j - next[j - 1];
break;
}
}
if (success == 1)
return i;
}

return -1;
}

//calculate KMP array


public int[] getNext(String needle) {
int[] next = new int[needle.length()];
next[0] = 0;

for (int i = 1; i < needle.length(); i++) {


int index = next[i - 1];
while (index > 0 && needle.charAt(index) != needle.charAt(i)) {
index = next[index - 1];
}

if (needle.charAt(index) == needle.charAt(i)) {
next[i] = next[i - 1] + 1;
} else {
next[i] = 0;
}
}

66 | 531 Program Creek

60 of
52 of 246
288
22 Implement strStr()

return next;
}

Program Creek 67 | 531

61 of
53 of 246
288
23 Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length
of a subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal
length of 2 under the problem constraint.

23.1 Analysis

We can use 2 points to mark the left and right boundaries of the sliding window. When
the sum is greater than the target, shift the left pointer; when the sum is less than the
target, shift the right pointer.

23.2 Java Solution 1

A simple sliding window solution.


public int minSubArrayLen(int s, int[] nums) {
if(nums==null || nums.length==1)
return 0;

int result = nums.length;

int start=0;
int sum=0;
int i=0;
boolean exists = false;

while(i<=nums.length){
if(sum>=s){
exists=true; //mark if there exists such a subarray
if(start==i-1){
return 1;
}

result = Math.min(result, i-start);


sum=sum-nums[start];
start++;

}else{
if(i==nums.length)
break;

69 | 531

63 of
54 of 246
288
23 Minimum Size Subarray Sum

sum = sum+nums[i];
i++;
}
}

if(exists)
return result;
else
return 0;
}

23.3 Deprecated Java Solution

This solution works but it is less readable.


public int minSubArrayLen(int s, int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
if(nums.length == 1 && nums[0] < s){
return 0;
}

// initialize min length to be the input array length


int result = nums.length;

int i = 0;
int sum = nums[0];

for(int j=0; j<nums.length; ){


if(i==j){
if(nums[i]>=s){
return 1; //if single elem is large enough
}else{
j++;

if(j<nums.length){
sum = sum + nums[j];
}else{
return result;
}
}
}else{
//if sum is large enough, move left cursor
if(sum >= s){
result = Math.min(j-i+1, result);
sum = sum - nums[i];
i++;

70 | 531 Program Creek

64 of
55 of 246
288
23 Minimum Size Subarray Sum

//if sum is not large enough, move right cursor


}else{
j++;

if(j<nums.length){
sum = sum + nums[j];
}else{
if(i==0){
return 0;
}else{
return result;
}
}
}
}
}

return result;
}

Program Creek 71 | 531

65 of
56 of 246
288
24 Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not,
return the index where it would be if it were inserted in order. You may assume no
duplicates in the array.
Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0

24.1 Solution 1

Naively, we can just iterate the array and compare target with ith and (i+1)th element.
Time complexity is O(n)
public class Solution {
public int searchInsert(int[] A, int target) {

if(A==null) return 0;

if(target <= A[0]) return 0;

for(int i=0; i<A.length-1; i++){


if(target > A[i] && target <= A[i+1]){
return i+1;
}
}

return A.length;
}
}

24.2 Solution 2

This also looks like a binary search problem. We should try to make the complexity to
be O(log(n)).
public class Solution {
public int searchInsert(int[] A, int target) {

73 | 531

67 of
57 of 246
288
24 Search Insert Position

if(A==null||A.length==0)
return 0;

return searchInsert(A,target,0,A.length-1);
}

public int searchInsert(int[] A, int target, int start, int end){


int mid=(start+end)/2;

if(target==A[mid])
return mid;
else if(target<A[mid])
return start<mid?searchInsert(A,target,start,mid-1):start;
else
return end>mid?searchInsert(A,target,mid+1,end):(end+1);
}
}

74 | 531 Program Creek

68 of
58 of 246
288
25 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements
sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence
should be [1, 2, 3, 4]. Its length is 4.
Your algorithm should run in O(n) complexity.

25.1 Analysis

Because it requires O(n) complexity, we can not solve the problem by sorting the array
first. Sorting takes at least O(nlogn) time.

25.2 Java Solution

We can use a HashSet to add and remove elements. HashSet is implemented by using
a hash table. Elements are not ordered. The add, remove and contains methods have
constant time complexity O(1).
public static int longestConsecutive(int[] num) {
// if array is empty, return 0
if (num.length == 0) {
return 0;
}

Set<Integer> set = new HashSet<Integer>();


int max = 1;

for (int e : num)


set.add(e);

for (int e : num) {


int left = e - 1;
int right = e + 1;
int count = 1;

while (set.contains(left)) {
count++;
set.remove(left);
left--;
}

75 | 531

69 of
59 of 246
288
25 Longest Consecutive Sequence

while (set.contains(right)) {
count++;
set.remove(right);
right++;
}

max = Math.max(count, max);


}

return max;
}

After an element is checked, it should be removed from the set. Otherwise, time
complexity would be O(mn) in which m is the average length of all consecutive se-
quences.
To clearly see the time complexity, I suggest you use some simple examples and
manually execute the program. For example, given an array 1,2,4,5,3, the program
time is m. m is the length of longest consecutive sequence.

76 | 531 Program Creek

70 of
60 of 246
288
26 Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric charac-


ters and ignoring cases.
For example, "Red rum, sir, is murder" is a palindrome, while "Programcreek is
awesome" is not.
Note: Have you consider that the string might be empty? This is a good question to
ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

26.1 Thoughts

From start and end loop though the string, i.e., char array. If it is not alpha or num-
ber, increase or decrease pointers. Compare the alpha and numeric characters. The
solution below is pretty straightforward.

26.2 Java Solution 1 - Naive

public class Solution {

public boolean isPalindrome(String s) {

if(s == null) return false;


if(s.length() < 2) return true;

char[] charArray = s.toCharArray();


int len = s.length();

int i=0;
int j=len-1;

while(i<j){
char left, right;

while(i<len-1 && !isAlpha(left) && !isNum(left)){


i++;
left = charArray[i];
}

while(j>0 && !isAlpha(right) && !isNum(right)){


j--;

77 | 531

71 of
61 of 246
288
26 Valid Palindrome

right = charArray[j];
}

if(i >= j)
break;

left = charArray[i];
right = charArray[j];

if(!isSame(left, right)){
return false;
}

i++;
j--;
}
return true;
}

public boolean isAlpha(char a){


if((a >= ’a’ && a <= ’z’) || (a >= ’A’ && a <= ’Z’)){
return true;
}else{
return false;
}
}

public boolean isNum(char a){


if(a >= ’0’ && a <= ’9’){
return true;
}else{
return false;
}
}

public boolean isSame(char a, char b){


if(isNum(a) && isNum(b)){
return a == b;
}else if(Character.toLowerCase(a) == Character.toLowerCase(b)){
return true;
}else{
return false;
}
}
}

78 | 531 Program Creek

72 of
62 of 246
288
26 Valid Palindrome

26.3 Java Solution 2 - Using Stack

This solution removes the special characters first. (Thanks to Tia)


public boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

int len = s.length();


if (len < 2)
return true;

Stack<Character> stack = new Stack<Character>();

int index = 0;
while (index < len / 2) {
stack.push(s.charAt(index));
index++;
}

if (len % 2 == 1)
index++;

while (index < len) {


if (stack.empty())
return false;

char temp = stack.pop();


if (s.charAt(index) != temp)
return false;
else
index++;
}

return true;
}

26.4 Java Solution 3 - Using Two Pointers

In the discussion below, April and Frank use two pointers to solve this problem. This
solution looks really simple.
public class ValidPalindrome {
public static boolean isValidPalindrome(String s){
if(s==null||s.length()==0) return false;

s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
System.out.println(s);

Program Creek 79 | 531

73 of
63 of 246
288
26 Valid Palindrome

for(int i = 0; i < s.length() ; i++){


if(s.charAt(i) != s.charAt(s.length() - 1 - i)){
return false;
}
}

return true;
}

public static void main(String[] args) {


String str = "A man, a plan, a canal: Panama";

System.out.println(isValidPalindrome(str));
}
}

80 | 531 Program Creek

74 of
64 of 246
288
27 ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of


rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R

And then read line by line: "PAHNAPLSIIGYIR" Write the a method convert("PAYPALISHIRING",
3) which returns "PAHNAPLSIIGYIR".

27.1 Java Solution

public String convert(String s, int numRows) {


if (numRows == 1)
return s;

StringBuilder sb = new StringBuilder();


// step
int step = 2 * numRows - 2;

for (int i = 0; i < numRows; i++) {


//first & last rows
if (i == 0 || i == numRows - 1) {
for (int j = i; j < s.length(); j = j + step) {
sb.append(s.charAt(j));
}
//middle rows
} else {
int j = i;
boolean flag = true;
int step1 = 2 * (numRows - 1 - i);
int step2 = step - step1;

while (j < s.length()) {


sb.append(s.charAt(j));
if (flag)
j = j + step1;
else
j = j + step2;
flag = !flag;
}

81 | 531

75 of
65 of 246
288
27 ZigZag Conversion

}
}

return sb.toString();
}

82 | 531 Program Creek

76 of
66 of 246
288
28 Add Binary

Given two binary strings, return their sum (also a binary string).
For example, a = "11", b = "1", the return is "100".

28.1 Java Solution

Very simple, nothing special. Note how to convert a character to an int.


public String addBinary(String a, String b) {
if(a==null || a.length()==0)
return b;
if(b==null || b.length()==0)
return a;

int pa = a.length()-1;
int pb = b.length()-1;

int flag = 0;
StringBuilder sb = new StringBuilder();
while(pa >= 0 || pb >=0){
int va = 0;
int vb = 0;

if(pa >= 0){


va = a.charAt(pa)==’0’? 0 : 1;
pa--;
}
if(pb >= 0){
vb = b.charAt(pb)==’0’? 0: 1;
pb--;
}

int sum = va + vb + flag;


if(sum >= 2){
sb.append(String.valueOf(sum-2));
flag = 1;
}else{
flag = 0;
sb.append(String.valueOf(sum));
}
}

if(flag == 1){

83 | 531

77 of
67 of 246
288
28 Add Binary

sb.append("1");
}

String reversed = sb.reverse().toString();


return reversed;
}

84 | 531 Program Creek

78 of
68 of 246
288
29 Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ’


’, return the length of last word in the string. If the last word does not exist, return 0.

29.1 Java Solution

Very simple question. We just need a flag to mark the start of letters from the end. If
a letter starts and the next character is not a letter, return the length.
public int lengthOfLastWord(String s) {
if(s==null || s.length() == 0)
return 0;

int result = 0;
int len = s.length();

boolean flag = false;


for(int i=len-1; i>=0; i--){
char c = s.charAt(i);
if((c>=’a’ && c<=’z’) || (c>=’A’ && c<=’Z’)){
flag = true;
result++;
}else{
if(flag)
return result;
}
}

return result;
}

85 | 531

79 of
69 of 246
288
30 Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may
move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).


Note: Bonus point if you are able to do this using only O(n) extra space, where n is
the total number of rows in the triangle.

30.1 Top-Down Approach (Wrong Answer!)

This solution gets wrong answer! I will try to make it work later.
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {

int[] temp = new int[triangle.size()];


int minTotal = Integer.MAX_VALUE;

for(int i=0; i< temp.length; i++){


temp[i] = Integer.MAX_VALUE;
}

if (triangle.size() == 1) {
return Math.min(minTotal, triangle.get(0).get(0));
}

int first = triangle.get(0).get(0);

for (int i = 0; i < triangle.size() - 1; i++) {


for (int j = 0; j <= i; j++) {

int a, b;

if(i==0 && j==0){

87 | 531

81 of
70 of 246
288
30 Triangle

a = first + triangle.get(i + 1).get(j);


b = first + triangle.get(i + 1).get(j + 1);

}else{
a = temp[j] + triangle.get(i + 1).get(j);
b = temp[j] + triangle.get(i + 1).get(j + 1);

temp[j] = Math.min(a, temp[j]);


temp[j + 1] = Math.min(b, temp[j + 1]);
}
}

for (int e : temp) {


if (e < minTotal)
minTotal = e;
}

return minTotal;
}
}

30.2 Bottom-Up (Good Solution)

We can actually start from the bottom of the triangle.


public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
int[] total = new int[triangle.size()];
int l = triangle.size() - 1;

for (int i = 0; i < triangle.get(l).size(); i++) {


total[i] = triangle.get(l).get(i);
}

// iterate from last second row


for (int i = triangle.size() - 2; i >= 0; i--) {
for (int j = 0; j < triangle.get(i + 1).size() - 1; j++) {
total[j] = triangle.get(i).get(j) + Math.min(total[j], total[j + 1]);
}
}

return total[0];
}

88 | 531 Program Creek

82 of
71 of 246
288
31 Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function
should return true if any value appears at least twice in the array, and it should return
false if every element is distinct.

31.1 Java Solution

public boolean containsDuplicate(int[] nums) {


if(nums==null || nums.length==0)
return false;

HashSet<Integer> set = new HashSet<Integer>();


for(int i: nums){
if(!set.add(i)){
return true;
}
}

return false;
}

89 | 531

83 of
72 of 246
288
32 Contains Duplicate II

Given an array of integers and an integer k, return true if and only if there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the difference
between i and j is at most k.

32.1 Java Solution 1

public boolean containsNearbyDuplicate(int[] nums, int k) {


HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int min = Integer.MAX_VALUE;

for(int i=0; i<nums.length; i++){


if(map.containsKey(nums[i])){
int preIndex = map.get(nums[i]);
int gap = i-preIndex;
min = Math.min(min, gap);
}
map.put(nums[i], i);
}

if(min <= k){


return true;
}else{
return false;
}
}

32.2 Java Solution 2 - Simplified

public boolean containsNearbyDuplicate(int[] nums, int k) {


HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

for(int i=0; i<nums.length; i++){


if(map.containsKey(nums[i])){
int pre = map.get(nums[i]);
if(i-pre<=k)
return true;
}

91 | 531

85 of
73 of 246
288
32 Contains Duplicate II

map.put(nums[i], i);
}

return false;
}

92 | 531 Program Creek

86 of
74 of 246
288
33 Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in
the array such that the difference between nums[i] and nums[j] is at most t and the
difference between i and j is at most k.

33.1 Java Solution 1

This solution uses a treeset.

The time complexity is O(nlog(k)).


public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0)
return false;

TreeSet<Integer> set = new TreeSet<Integer>();

for (int i = 0; i < nums.length; i++) {


int c = nums[i];
if ((set.floor(c) != null && c <= set.floor(c) + t)
|| (set.ceiling(c) != null && c >= set.ceiling(c) -t))
return true;

set.add(c);

if (i >= k)
set.remove(nums[i - k]);
}

return false;
}

93 | 531

87 of
75 of 246
288
33 Contains Duplicate III

33.2 Java Solution 2

Another solution that is easier to understand.


public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0)
return false;

SortedSet<Long> set = new TreeSet<Long>();

for (int j = 0; j < nums.length; j++) {


long leftBoundary = (long) nums[j] - t;
long rightBoundary = (long) nums[j] + t + 1;
SortedSet<Long> subSet = set.subSet(leftBoundary, rightBoundary);

if (!subSet.isEmpty())
return true;

set.add((long) nums[j]);

if (j >= k) {
set.remove((long) nums[j - k]);
}
}

return false;
}

94 | 531 Program Creek

88 of
76 of 246
288
34 Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear
only once and return the new length. Do not allocate extra space for another array,
you must do this in place with constant memory.
For example, given input array A = [1,1,2], your function should return length = 2,
and A is now [1,2].

34.1 Thoughts

The problem is pretty straightforward. It returns the length of array with unique
elements, but the original array need to be changed also. This problem should be
reviewed with Remove Duplicates from Sorted Array II.

34.2 Solution 1

// Manipulate original array


public static int removeDuplicatesNaive(int[] A) {
if (A.length < 2)
return A.length;

int j = 0;
int i = 1;

while (i < A.length) {


if (A[i] == A[j]) {
i++;
} else {
j++;
A[j] = A[i];
i++;
}
}

return j + 1;
}

This method returns the number of unique elements, but does not change the orig-
inal array correctly. For example, if the input array is 1, 2, 2, 3, 3, the array will be
changed to 1, 2, 3, 3, 3. The correct result should be 1, 2, 3. Because array’s size can

95 | 531

89 of
77 of 246
288
34 Remove Duplicates from Sorted Array

not be changed once created, there is no way we can return the original array with
correct results.

34.3 Solution 2

// Create an array with all unique elements


public static int[] removeDuplicates(int[] A) {
if (A.length < 2)
return A;

int j = 0;
int i = 1;

while (i < A.length) {


if (A[i] == A[j]) {
i++;
} else {
j++;
A[j] = A[i];
i++;
}
}

int[] B = Arrays.copyOf(A, j + 1);

return B;
}

public static void main(String[] args) {


int[] arr = { 1, 2, 2, 3, 3 };
arr = removeDuplicates(arr);
System.out.println(arr.length);
}

In this method, a new array is created and returned.

34.4 Solution 3

If we only want to count the number of unique elements, the following method is
good enough.
// Count the number of unique elements
public static int countUnique(int[] A) {
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] == A[i + 1]) {
count++;

96 | 531 Program Creek

90 of
78 of 246
288
34 Remove Duplicates from Sorted Array

}
}
return (A.length - count);
}

public static void main(String[] args) {


int[] arr = { 1, 2, 2, 3, 3 };
int size = countUnique(arr);
System.out.println(size);
}

Program Creek 97 | 531

91 of
79 of 246
288
35 Remove Duplicates from Sorted Array
II

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3], your function should return length
= 5, and A is now [1,1,2,2,3].

35.1 Naive Approach

Given the method signature "public int removeDuplicates(int[] A)", it seems that we
should write a method that returns a integer and that’s it. After typing the following
solution:
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0)
return 0;

int pre = A[0];


boolean flag = false;
int count = 0;

for(int i=1; i<A.length; i++){


int curr = A[i];

if(curr == pre){
if(!flag){
flag = true;
continue;
}else{
count++;
}
}else{
pre = curr;
flag = false;
}
}

return A.length - count;


}
}

99 | 531

93 of
80 of 246
288
35 Remove Duplicates from Sorted Array II

Online Judge returns:


Submission Result: Wrong Answer
Input: [1,1,1,2]
Output: [1,1,1]
Expected: [1,1,2]

So this problem also requires in-place array manipulation.

35.2 Correct Solution

We can not change the given array’s size, so we only change the first k elements of the
array which has duplicates removed.
public class Solution {
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0)
return 0;

int pre = A[0];


boolean flag = false;
int count = 0;

// index for updating


int o = 1;

for (int i = 1; i < A.length; i++) {


int curr = A[i];

if (curr == pre) {
if (!flag) {
flag = true;
A[o++] = curr;

continue;
} else {
count++;
}
} else {
pre = curr;
A[o++] = curr;
flag = false;
}
}

return A.length - count;


}
}

100 | 531 Program Creek

94 of
81 of 246
288
35 Remove Duplicates from Sorted Array II

35.3 Better Solution

public class Solution {


public int removeDuplicates(int[] A) {
if (A.length <= 2)
return A.length;

int prev = 1; // point to previous


int curr = 2; // point to current

while (curr < A.length) {


if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
curr++;
} else {
prev++;
A[prev] = A[curr];
curr++;
}
}

return prev + 1;
}
}

Program Creek 101 | 531

95 of
82 of 246
288
36 Longest Substring Without Repeating
Characters

Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc",
which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

36.1 Java Solution 1

The first solution is like the problem of "determine if a string has all unique characters"
in CC 150. We can use a flag array to track the existing characters for the longest
substring without repeating characters.
public int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
boolean[] flag = new boolean[256];

int result = 0;
int start = 0;
char[] arr = s.toCharArray();

for (int i = 0; i < arr.length; i++) {


char current = arr[i];
if (flag[current]) {
result = Math.max(result, i - start);
// the loop update the new start point
// and reset flag array
// for example, abccab, when it comes to 2nd c,
// it update start from 0 to 3, reset flag for a,b
for (int k = start; k < i; k++) {
if (arr[k] == current) {
start = k + 1;
break;
}
flag[arr[k]] = false;
}
} else {
flag[current] = true;
}
}

103 | 531

97 of
83 of 246
288
36 Longest Substring Without Repeating Characters

result = Math.max(arr.length - start, result);

return result;
}

36.2 Java Solution 2

This solution is from Tia. It is easier to understand than the first solution.
The basic idea is using a hash table to track existing characters and their posi-
tion. When a repeated character occurs, check from the previously repeated character.
However, the time complexity is higher - O(n3̂).
public static int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
char[] arr = s.toCharArray();
int pre = 0;

HashMap<Character, Integer> map = new HashMap<Character, Integer>();

for (int i = 0; i < arr.length; i++) {


if (!map.containsKey(arr[i])) {
map.put(arr[i], i);
} else {
pre = Math.max(pre, map.size());
i = map.get(arr[i]);
map.clear();
}
}

return Math.max(pre, map.size());


}

Consider the following simple example.


abcda

When loop hits the second "a", the HashMap contains the following:
a 0
b 1
c 2
d 3

The index i is set to 0 and incremented by 1, so the loop start from second element
again.

104 | 531 Program Creek

98 of
84 of 246
288
37 Longest Substring Which Contains 2
Unique Characters

This is a problem asked by Google.


Given a string, find the longest substring that contains only two unique charac-
ters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains
2 unique character is "bcbbbbcccb".

37.1 Longest Substring Which Contains 2 Unique


Characters

In this solution, a hashmap is used to track the unique elements in the map. When a
third character is added to the map, the left pointer needs to move right.
You can use "abac" to walk through this solution.
public int lengthOfLongestSubstringTwoDistinct(String s) {
int max=0;
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
int start=0;

for(int i=0; i<s.length(); i++){


char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else{
map.put(c,1);
}

if(map.size()>2){
max = Math.max(max, i-start);

while(map.size()>2){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}

105 | 531

99 of
85 of 246
288
37 Longest Substring Which Contains 2 Unique Characters

}
}

max = Math.max(max, s.length()-start);

return max;
}

Now if this question is extended to be "the longest substring that contains k unique
characters", what should we do?

37.2 Solution for K Unique Characters

The following solution is corrected. Given "abcadcacacaca" and 3, it returns "cadcaca-


caca".
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int max=0;
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
int start=0;

for(int i=0; i<s.length(); i++){


char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else{
map.put(c,1);
}

if(map.size()>k){
max = Math.max(max, i-start);

while(map.size()>k){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
}
}

max = Math.max(max, s.length()-start);

return max;
}

106 | 531 Program Creek

86 of
100 of246
288
37 Longest Substring Which Contains 2 Unique Characters

Time is O(n).

Program Creek 107 | 531

87 of
101 of246
288
38 Substring with Concatenation of All
Words

You are given a string, s, and a list of words, words, that are all of the same length.
Find all starting indices of substring(s) in s that is a concatenation of each word in
words exactly once and without any intervening characters.
For example, given: s="barfoothefoobarman" & words=["foo", "bar"], return [0,9].

38.1 Analysis

This problem is similar (almost the same) to Longest Substring Which Contains 2
Unique Characters.
Since each word in the dictionary has the same length, each of them can be treated
as a single character.

38.2 Java Solution

public List<Integer> findSubstring(String s, String[] words) {


ArrayList<Integer> result = new ArrayList<Integer>();
if(s==null||s.length()==0||words==null||words.length==0){
return result;
}

//frequency of words
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String w: words){
if(map.containsKey(w)){
map.put(w, map.get(w)+1);
}else{
map.put(w, 1);
}
}

int len = words[0].length();

for(int j=0; j<len; j++){


HashMap<String, Integer> currentMap = new HashMap<String, Integer>();
int start = j;//start index of start
int count = 0;//count totoal qualified words so far

109 | 531

88 of
103 of246
288
38 Substring with Concatenation of All Words

for(int i=j; i<=s.length()-len; i=i+len){


String sub = s.substring(i, i+len);
if(map.containsKey(sub)){
//set frequency in current map
if(currentMap.containsKey(sub)){
currentMap.put(sub, currentMap.get(sub)+1);
}else{
currentMap.put(sub, 1);
}

count++;

while(currentMap.get(sub)>map.get(sub)){
String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);

count--;
start = start + len;
}

if(count==words.length){
result.add(start); //add to result

//shift right and reset currentMap, count & start point


String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);
count--;
start = start + len;
}
}else{
currentMap.clear();
start = i+len;
count = 0;
}
}
}

return result;
}

110 | 531 Program Creek

89 of
104 of246
288
39 Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all
the characters in T in complexity O(n).
For example, S = "ADOBECODEBANC", T = "ABC", Minimum window is "BANC".

39.1 Java Solution

public String minWindow(String s, String t) {


if(t.length()>s.length())
return "";
String result = "";

//character counter for t


HashMap<Character, Integer> target = new HashMap<Character, Integer>();
for(int i=0; i<t.length(); i++){
char c = t.charAt(i);
if(target.containsKey(c)){
target.put(c,target.get(c)+1);
}else{
target.put(c,1);
}
}

// character counter for s


HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int left = 0;
int minLen = s.length()+1;

int count = 0; // the total of mapped characters

for(int i=0; i<s.length(); i++){


char c = s.charAt(i);

if(target.containsKey(c)){
if(map.containsKey(c)){
if(map.get(c)<target.get(c)){
count++;
}
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
count++;

111 | 531

90 of
105 of246
288
39 Minimum Window Substring

}
}

if(count == t.length()){
char sc = s.charAt(left);
while (!map.containsKey(sc) || map.get(sc) > target.get(sc)) {
if (map.containsKey(sc) && map.get(sc) > target.get(sc))
map.put(sc, map.get(sc) - 1);
left++;
sc = s.charAt(left);
}

if (i - left + 1 < minLen) {


result = s.substring(left, i + 1);
minLen = i - left + 1;
}
}
}

return result;
}

112 | 531 Program Creek

91 of
106 of246
288
40 Reverse Words in a String

Given an input string, reverse the string word by word.


For example, given s = "the sky is blue", return "blue is sky the".

40.1 Java Solution

This problem is pretty straightforward. We first split the string to words array, and
then iterate through the array and add each element to a new string. Note: String-
Builder should be used to avoid creating too many Strings. If the string is very long,
using String is not scalable since String is immutable and too many objects will be
created and garbage collected.
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}

// split to words by space


String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}

113 | 531

92 of
107 of246
288
41 Find Minimum in Rotated Sorted
Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1
2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.You may assume no duplicate exists in the array.

41.1 Analysis

This problem is a binary search and the key is breaking the array to two parts, so that
we only need to work on half of the array each time.
If we pick the middle element, we can compare the middle element with the leftmost
(or rightmost) element. If the middle element is less than leftmost, the left half should
be selected; if the middle element is greater than the leftmost (or rightmost), the right
half should be selected. Using recursion or iteration, this problem can be solved in
time log(n).
In addition, in any rotated sorted array, the rightmost element should be less than
the left-most element, otherwise, the sorted array is not rotated and we can simply
pick the leftmost element as the minimum.

41.2 Java Solution 1 - Recursion

Define a helper function, otherwise, we will need to use Arrays.copyOfRange() func-


tion, which may be expensive for large arrays.
public int findMin(int[] num) {
return findMin(num, 0, num.length - 1);
}

public int findMin(int[] num, int left, int right) {


if (left == right)
return num[left];
if ((right - left) == 1)
return Math.min(num[left], num[right]);

int middle = left + (right - left) / 2;

// not rotated
if (num[left] < num[right]) {
return num[left];

115 | 531

93 of
109 of246
288
41 Find Minimum in Rotated Sorted Array

// go right side
} else if (num[middle] > num[left]) {
return findMin(num, middle, right);

// go left side
} else {
return findMin(num, left, middle);
}
}

41.3 Java Solution 2 - Iteration

public int findMin(int[] nums) {


if(nums.length==1)
return nums[0];

int left=0;
int right=nums.length-1;

//not rotated
if(nums[left]<nums[right])
return nums[left];

while(left <= right){


if(right-left==1){
return nums[right];
}

int m = left + (right-left)/2;

if(nums[m] > nums[right])


left = m;
else
right = m;
}

return nums[left];
}

116 | 531 Program Creek

94 of
110 of246
288
42 Find Minimum in Rotated Sorted
Array II

42.1 Problem

Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are al-
lowed?
Would this affect the run-time complexity? How and why?

42.2 Java Solution

This is a follow-up problem of finding minimum element in rotated sorted array with-
out duplicate elements. We only need to add one more condition, which checks if
the left-most element and the right-most element are equal. If they are we can simply
drop one of them. In my solution below, I drop the left element whenever the left-most
equals to the right-most.
public int findMin(int[] num) {
return findMin(num, 0, num.length-1);
}

public int findMin(int[] num, int left, int right){


if(right==left){
return num[left];
}
if(right == left +1){
return Math.min(num[left], num[right]);
}
// 3 3 1 3 3 3

int middle = (right-left)/2 + left;


// already sorted
if(num[right] > num[left]){
return num[left];
//right shift one
}else if(num[right] == num[left]){
return findMin(num, left+1, right);
//go right
}else if(num[middle] >= num[left]){
return findMin(num, middle, right);
//go left

117 | 531

95 of
111 of246
288
42 Find Minimum in Rotated Sorted Array II

}else{
return findMin(num, left, middle);
}
}

118 | 531 Program Creek

96 of
112 of246
288
43 Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1
2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, other-
wise return -1. You may assume no duplicate exists in the array.

43.1 Java Solution 1- Recusive

public int search(int[] nums, int target) {


return binarySearch(nums, 0, nums.length-1, target);
}

public int binarySearch(int[] nums, int left, int right, int target){
if(left>right)
return -1;

int mid = left + (right-left)/2;

if(target == nums[mid])
return mid;

if(nums[left] <= nums[mid]){


if(nums[left]<=target && target<nums[mid]){
return binarySearch(nums,left, mid-1, target);
}else{
return binarySearch(nums, mid+1, right, target);
}
}else {
if(nums[mid]<target&& target<=nums[right]){
return binarySearch(nums,mid+1, right, target);
}else{
return binarySearch(nums, left, mid-1, target);
}
}
}

43.2 Java Solution 2 - Iterative

public int search(int[] nums, int target) {

119 | 531

97 of
113 of246
288
43 Search in Rotated Sorted Array

int left = 0;
int right= nums.length-1;

while(left<=right){
int mid = left + (right-left)/2;
if(target==nums[mid])
return mid;

if(nums[left]<=nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{
if(nums[mid]<target&& target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}
}

return -1;
}

120 | 531 Program Creek

98 of
114 of246
288
44 Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array": what if duplicates are allowed? Write
a function to determine if a given target is in the array.

44.1 Java Solution

public boolean search(int[] nums, int target) {


int left=0;
int right=nums.length-1;

while(left<=right){
int mid = (left+right)/2;
if(nums[mid]==target)
return true;

if(nums[left]<nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else if(nums[left]>nums[mid]){
if(nums[mid]<target&&target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}else{
left++;
}
}

return false;
}

121 | 531

99 of
115 of246
288
45 Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in
constant time.
push(x) – Push element x onto stack. pop() – Removes the element on top of the
stack. top() – Get the top element. getMin() – Retrieve the minimum element in the
stack.

45.1 Analysis

UPDATED ON 6/17/2015
To make constant time of getMin(), we need to keep track of the minimum element
for each element in the stack.

45.2 Java Solution

Define a node class that holds element value, min value, and pointer to elements below
it.
class Node {
int value;
int min;
Node next;

Node(int x) {
value = x;
next = null;
min = x;
}
}

class MinStack {
Node head;

public void push(int x) {


if (head == null) {
head = new Node(x);
} else {
Node temp = new Node(x);
temp.min = Math.min(head.min, x);
temp.next = head;

123 | 531

117 of
100 of 246
288
45 Min Stack

head = temp;
}
}

public void pop() {


if (head == null)
return;
head = head.next;
}

public int top() {


if (head == null)
return Integer.MAX_VALUE;

return head.value;
}

public int getMin() {


if (head == null)
return Integer.MAX_VALUE;

return head.min;
}
}

124 | 531 Program Creek

118 of
101 of 246
288
46 Majority Element

Given an array of size n, find the majority element. The majority element is the element
that appears more than # n/2 $ times. (assume that the array is non-empty and the
majority element always exist in the array.)

46.1 Java Solution 1 - Naive

We can sort the array first, which takes time of nlog(n). Then scan once to find the
longest consecutive substrings.
public class Solution {
public int majorityElement(int[] num) {
if(num.length==1){
return num[0];
}

Arrays.sort(num);

int prev=num[0];
int count=1;
for(int i=1; i<num.length; i++){
if(num[i] == prev){
count++;
if(count > num.length/2) return num[i];
}else{
count=1;
prev = num[i];
}
}

return 0;
}
}

46.2 Java Solution 2 - Much Simpler

Thanks to SK. His/her solution is much efficient and simpler. Since the majority al-
ways take more than a half space, the middle element is guaranteed to be the majority.
Sorting array takes nlog(n). So the time complexity of this solution is nlog(n). Cheers!

125 | 531

119 of
102 of 246
288
46 Majority Element

public int majorityElement(int[] num) {


if (num.length == 1) {
return num[0];
}

Arrays.sort(num);
return num[num.length / 2];
}

46.3 Java Solution 3 - Linear Time Majority Vote Algorithm

public int majorityElement(int[] nums) {


int result = 0, count = 0;

for(int i = 0; i<nums.length; i++ ) {


if(count == 0){
result = nums[ i ];
count = 1;
}else if(result == nums[i]){
count++;
}else{
count--;
}
}

return result;
}

126 | 531 Program Creek

120 of
103 of 246
288
47 Majority Element II

Given an integer array of size n, find all elements that appear more than # n/3 $ times.
The algorithm should run in linear time and in O(1) space.

47.1 Java Solution 1 - Using a Counter

Time = O(n) and Space = O(n)


public List<Integer> majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i: nums){
if(map.containsKey(i)){
map.put(i, map.get(i)+1);
}else{
map.put(i, 1);
}
}

List<Integer> result = new ArrayList<Integer>();

for(Map.Entry<Integer, Integer> entry: map.entrySet()){


if(entry.getValue() > nums.length/3){
result.add(entry.getKey());
}
}

return result;
}

47.2 Java Solution 2

Time = O(n) and Space = O(1)


Check out Majority Element I.
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<Integer>();

Integer n1=null, n2=null;


int c1=0, c2=0;

for(int i: nums){

127 | 531

121 of
104 of 246
288
47 Majority Element II

if(n1!=null && i==n1.intValue()){


c1++;
}else if(n2!=null && i==n2.intValue()){
c2++;
}else if(c1==0){
c1=1;
n1=i;
}else if(c2==0){
c2=1;
n2=i;
}else{
c1--;
c2--;
}
}

c1=c2=0;

for(int i: nums){
if(i==n1.intValue()){
c1++;
}else if(i==n2.intValue()){
c2++;
}
}

if(c1>nums.length/3)
result.add(n1);
if(c2>nums.length/3)
result.add(n2);

return result;
}

128 | 531 Program Creek

122 of
105 of 246
288
48 Remove Element

Given an array and a value, remove all instances of that value in place and return the
new length. (Note: The order of elements can be changed. It doesn’t matter what you
leave beyond the new length.)

48.1 Java Solution

This problem can be solve by using two indices.


public int removeElement(int[] A, int elem) {
int i=0;
int j=0;

while(j < A.length){


if(A[j] != elem){
A[i] = A[j];
i++;
}

j++;
}

return i;
}

129 | 531

123 of
106 of 246
288
49 Largest Rectangle in Histogram

Given n non-negative integers representing the histogram’s bar height where the width
of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

For example, given height = [2,1,5,6,2,3], return 10.

49.1 Analysis

The key to solve this problem is to maintain a stack to store bars’ indexes. The stack
only keeps the increasing bars.

131 | 531

125 of
107 of 246
288
49 Largest Rectangle in Histogram

49.2 Java Solution

public int largestRectangleArea(int[] height) {


if (height == null || height.length == 0) {
return 0;
}

Stack<Integer> stack = new Stack<Integer>();

int max = 0;
int i = 0;

while (i < height.length) {


//push index to stack when the current height is larger than the previous
one
if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
stack.push(i);
i++;
} else {
//calculate max value when the current height is less than the previous
one
int p = stack.pop();
int h = height[p];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(h * w, max);
}

while (!stack.isEmpty()) {
int p = stack.pop();
int h = height[p];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(h * w, max);
}

return max;
}

132 | 531 Program Creek

126 of
108 of 246
288
50 Longest Common Prefix

50.1 Problem

Write a function to find the longest common prefix string amongst an array of strings.

50.2 Analysis

To solve this problem, we need to find the two loop conditions. One is the length of
the shortest string. The other is iteration over every element of the string array.

50.3 Java Solution

public String longestCommonPrefix(String[] strs) {


if(strs == null || strs.length == 0)
return "";

int minLen=Integer.MAX_VALUE;
for(String str: strs){
if(minLen > str.length())
minLen = str.length();
}
if(minLen == 0) return "";

for(int j=0; j<minLen; j++){


char prev=’0’;
for(int i=0; i<strs.length ;i++){
if(i==0) {
prev = strs[i].charAt(j);
continue;
}

if(strs[i].charAt(j) != prev){
return strs[i].substring(0, j);
}
}
}

return strs[0].substring(0,minLen);
}

133 | 531

127 of
109 of 246
288
51 Largest Number

Given a list of non negative integers, arrange them such that they form the largest
number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. (Note:
The result may be very large, so you need to return a string instead of an integer.)

51.1 Analysis

This problem can be solve by simply sorting strings, not sorting integer. Define a
comparator to compare strings by concat() right-to-left or left-to-right.

51.2 Java Solution

public String largestNumber(int[] nums) {


String[] strs = new String[nums.length];
for(int i=0; i<nums.length; i++){
strs[i] = String.valueOf(nums[i]);
}

Arrays.sort(strs, new Comparator<String>(){


public int compare(String s1, String s2){
String leftRight = s1+s2;
String rightLeft = s2+s1;
return -leftRight.compareTo(rightLeft);

}
});

StringBuilder sb = new StringBuilder();


for(String s: strs){
sb.append(s);
}

while(sb.charAt(0)==’0’ && sb.length()>1){


sb.deleteCharAt(0);
}

return sb.toString();
}

135 | 531

129 of
110 of 246
288
52 Simplify Path

Given an absolute path for a file (Unix-style), simplify it.


For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/../", => "/"
path = "/home//foo/", => "/home/foo"

52.1 Java Solution

public String simplifyPath(String path) {


Stack<String> stack = new Stack<String>();

//stack.push(path.substring(0,1));

while(path.length()> 0 && path.charAt(path.length()-1) ==’/’){


path = path.substring(0, path.length()-1);
}

int start = 0;
for(int i=1; i<path.length(); i++){
if(path.charAt(i) == ’/’){
stack.push(path.substring(start, i));
start = i;
}else if(i==path.length()-1){
stack.push(path.substring(start));
}
}

LinkedList<String> result = new LinkedList<String>();


int back = 0;
while(!stack.isEmpty()){
String top = stack.pop();

if(top.equals("/.") || top.equals("/")){
//nothing
}else if(top.equals("/..")){
back++;
}else{
if(back > 0){

137 | 531

131 of
111 of 246
288
52 Simplify Path

back--;
}else{
result.push(top);
}
}
}

//if empty, return "/"


if(result.isEmpty()){
return "/";
}

StringBuilder sb = new StringBuilder();


while(!result.isEmpty()){
String s = result.pop();
sb.append(s);
}

return sb.toString();
}

138 | 531 Program Creek

132 of
112 of 246
288
53 Compare Version Numbers

53.1 Problem

Compare two version numbers version1 and version2. If version1 >version2 return 1,
if version1 <version2 return -1, otherwise return 0. You may assume that the version
strings are non-empty and contain only digits and the . character. The . character does
not represent a decimal point and is used to separate number sequences. Here is an
example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37

53.2 Java Solution

The tricky part of the problem is to handle cases like 1.0 and 1. They should be equal.
public int compareVersion(String version1, String version2) {
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");

int i=0;
while(i<arr1.length || i<arr2.length){
if(i<arr1.length && i<arr2.length){
if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])){
return -1;
}else if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])){
return 1;
}
} else if(i<arr1.length){
if(Integer.parseInt(arr1[i]) != 0){
return 1;
}
} else if(i<arr2.length){
if(Integer.parseInt(arr2[i]) != 0){
return -1;
}
}

i++;
}

return 0;

139 | 531

133 of
113 of 246
288
53 Compare Version Numbers

140 | 531 Program Creek

134 of
114 of 246
288
54 Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is
gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from
station i to its next station (i+1). You begin the journey with an empty tank at one of
the gas stations.
Return the starting gas station’s index if you can travel around the circuit once,
otherwise return -1.

54.1 Analysis

To solve this problem, we need to understand and use the following 2 facts: 1) if the
sum of gas >= the sum of cost, then the circle can be completed. 2) if A can not reach
C in a the sequence of A–>B–>C, then B can not make it either.
Proof of fact 2:
If gas[A] < cost[A], then A can not even reach B.
So to reach C from A, gas[A] must >= cost[A].
Given that A can not reach C, we have gas[A] + gas[B] < cost[A] + cost[B],
and gas[A] >= cost[A],
Therefore, gas[B] < cost[B], i.e., B can not reach C.

54.2 Java Solution

public int canCompleteCircuit(int[] gas, int[] cost) {


int sumRemaining = 0; // track current remaining
int total = 0; // track total remaining
int start = 0;

for (int i = 0; i < gas.length; i++) {

141 | 531

135 of
115 of 246
288
54 Gas Station

int remaining = gas[i] - cost[i];

//if sum remaining of (i-1) >= 0, continue


if (sumRemaining >= 0) {
sumRemaining += remaining;
//otherwise, reset start index to be current
} else {
sumRemaining = remaining;
start = i;
}
total += remaining;
}

if (total >= 0){


return start;
}else{
return -1;
}
}

142 | 531 Program Creek

136 of
116 of 246
288
55 Pascal’s Triangle

Given numRows, generate the first numRows of Pascal’s triangle. For example, given
numRows = 5, the result should be:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

55.1 Java Solution

public ArrayList<ArrayList<Integer>> generate(int numRows) {


ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (numRows <= 0)
return result;

ArrayList<Integer> pre = new ArrayList<Integer>();


pre.add(1);
result.add(pre);

for (int i = 2; i <= numRows; i++) {


ArrayList<Integer> cur = new ArrayList<Integer>();

cur.add(1); //first
for (int j = 0; j < pre.size() - 1; j++) {
cur.add(pre.get(j) + pre.get(j + 1)); //middle
}
cur.add(1);//last

result.add(cur);
pre = cur;
}

return result;
}

143 | 531

137 of
117 of 246
288
56 Pascal’s Triangle II

Given an index k, return the kth row of the Pascal’s triangle. For example, when k =
3, the row is [1,3,3,1].

56.1 Analysis

This problem is related to Pascal’s Triangle which gets all rows of Pascal’s triangle. In
this problem, only one row is required to return.

56.2 Java Solution

public List<Integer> getRow(int rowIndex) {


ArrayList<Integer> result = new ArrayList<Integer>();

if (rowIndex < 0)
return result;

result.add(1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = result.size() - 2; j >= 0; j--) {
result.set(j + 1, result.get(j) + result.get(j + 1));
}
result.add(1);
}
return result;
}

145 | 531

139 of
118 of 246
288
57 Container With Most Water

57.1 Problem

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordi-
nate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai)
and (i, 0). Find two lines, which together with x-axis forms a container, such that the
container contains the most water.

57.2 Analysis

Initially we can assume the result is 0. Then we scan from both sides. If leftHeight
<rightHeight, move right and find a value that is greater than leftHeight. Similarily,
if leftHeight >rightHeight, move left and find a value that is greater than rightHeight.
Additionally, keep tracking the max value.

57.3 Java Solution

public int maxArea(int[] height) {


if (height == null || height.length < 2) {
return 0;
}

int max = 0;
int left = 0;
int right = height.length - 1;

while (left < right) {


max = Math.max(max, (right - left) * Math.min(height[left],
height[right]));

147 | 531

141 of
119 of 246
288
57 Container With Most Water

if (height[left] < height[right])


left++;
else
right--;
}

return max;
}

148 | 531 Program Creek

142 of
120 of 246
288
58 Candy

There are N children standing in a line. Each child is assigned a rating value. You are
giving candies to these children subjected to the following requirements:
1. Each child must have at least one candy. 2. Children with a higher rating get
more candies than their neighbors.
What is the minimum candies you must give?

58.1 Analysis

This problem can be solved in O(n) time.


We can always assign a neighbor with 1 more if the neighbor has higher a rating
value. However, to get the minimum total number, we should always start adding 1s
in the ascending order. We can solve this problem by scanning the array from both
sides. First, scan the array from left to right, and assign values for all the ascending
pairs. Then scan from right to left and assign values to descending pairs.
This problem is similar to Trapping Rain Water.

58.2 Java Solution

public int candy(int[] ratings) {


if (ratings == null || ratings.length == 0) {
return 0;
}

int[] candies = new int[ratings.length];


candies[0] = 1;

//from let to right


for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
} else {
// if not ascending, assign 1
candies[i] = 1;
}
}

int result = candies[ratings.length - 1];

149 | 531

143 of
121 of 246
288
58 Candy

//from right to left


for (int i = ratings.length - 2; i >= 0; i--) {
int cur = 1;
if (ratings[i] > ratings[i + 1]) {
cur = candies[i + 1] + 1;
}

result += Math.max(cur, candies[i]);


candies[i] = cur;
}

return result;
}

150 | 531 Program Creek

144 of
122 of 246
288
59 Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each
bar is 1, compute how much water it is able to trap after raining.
For example, given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

59.1 Analysis

This problem is similar to Candy. It can be solve by scanning from both sides and
then get the total.

59.2 Java Solution

public int trap(int[] height) {


int result = 0;

if(height==null || height.length<=2)
return result;

int left[] = new int[height.length];


int right[]= new int[height.length];

//scan from left to right


int max = height[0];
left[0] = height[0];
for(int i=1; i<height.length; i++){
if(height[i]<max){
left[i]=max;
}else{
left[i]=height[i];
max = height[i];
}
}

//scan from right to left


max = height[height.length-1];
right[height.length-1]=height[height.length-1];
for(int i=height.length-2; i>=0; i--){
if(height[i]<max){
right[i]=max;
}else{

151 | 531

145 of
123 of 246
288
59 Trapping Rain Water

right[i]=height[i];
max = height[i];
}
}

//calculate totoal
for(int i=0; i<height.length; i++){
result+= Math.min(left[i],right[i])-height[i];
}

return result;
}

152 | 531 Program Creek

146 of
124 of 246
288
60 Count and Say

60.1 Problem

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21,
1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

60.2 Java Solution

The problem can be solved by using a simple iteration. See Java solution below:
public String countAndSay(int n) {
if (n <= 0)
return null;

String result = "1";


int i = 1;

while (i < n) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == result.charAt(j - 1)) {
count++;
} else {
sb.append(count);
sb.append(result.charAt(j - 1));
count = 1;
}
}

sb.append(count);
sb.append(result.charAt(result.length() - 1));
result = sb.toString();
i++;
}

153 | 531

147 of
125 of 246
288
60 Count and Say

return result;
}

154 | 531 Program Creek

148 of
126 of 246
288
61 Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target
value. Your algorithm’s runtime complexity must be in the order of O(log n). If the
target is not found in the array, return [-1, -1]. For example, given [5, 7, 7, 8, 8, 10] and
target value 8, return [3, 4].

61.1 Analysis

Based on the requirement of O(log n), this is a binary search problem apparently.

61.2 Java Solution

public int[] searchRange(int[] nums, int target) {


if(nums == null || nums.length == 0){
return null;
}

int[] arr= new int[2];


arr[0]=-1;
arr[1]=-1;

binarySearch(nums, 0, nums.length-1, target, arr);

return arr;
}

public void binarySearch(int[] nums, int left, int right, int target, int[]
arr){
if(right<left)
return;

if(nums[left]==nums[right] && nums[left]==target){


arr[0]=left;
arr[1]=right;
return;
}

int mid = left+(right-left)/2;

155 | 531

149 of
127 of 246
288
61 Search for a Range

if(nums[mid]<target){
binarySearch(nums, mid+1, right, target, arr);
}else if(nums[mid]>target){
binarySearch(nums, left, mid-1, target, arr);
}else{
arr[0]=mid;
arr[1]=mid;

//handle duplicates - left


int t1 = mid;
while(t1 >left && nums[t1]==nums[t1-1]){
t1--;
arr[0]=t1;
}

//handle duplicates - right


int t2 = mid;
while(t2 < right&& nums[t2]==nums[t2+1]){
t2++;
arr[1]=t2;
}
return;
}
}

156 | 531 Program Creek

150 of
128 of 246
288
62 Basic Calculator

Implement a basic calculator to evaluate a simple expression string.


The expression string may contain open ( and closing parentheses ), the plus + or
minus sign -, non-negative integers and empty spaces.You may assume that the given
expression is always valid.
Some examples: "1 + 1" = 2, "(1)" = 1, "(1-(4-5))" = 2

62.1 Analysis

This problem can be solved by using a stack. We keep pushing element to the stack,
when ’)" is met, calculate the expression up to the first "(".

62.2 Java Solution

public int calculate(String s) {


// delte white spaces
s = s.replaceAll(" ", "");

Stack<String> stack = new Stack<String>();


char[] arr = s.toCharArray();

StringBuilder sb = new StringBuilder();


for (int i = 0; i < arr.length; i++) {
if (arr[i] == ’ ’)
continue;

if (arr[i] >= ’0’ && arr[i] <= ’9’) {


sb.append(arr[i]);

if (i == arr.length - 1) {
stack.push(sb.toString());
}
} else {
if (sb.length() > 0) {
stack.push(sb.toString());
sb = new StringBuilder();
}

if (arr[i] != ’)’) {
stack.push(new String(new char[] { arr[i] }));

157 | 531

151 of
129 of 246
288
62 Basic Calculator

} else {
// when meet ’)’, pop and calculate
ArrayList<String> t = new ArrayList<String>();
while (!stack.isEmpty()) {
String top = stack.pop();
if (top.equals("(")) {
break;
} else {
t.add(0, top);
}
}

int temp = 0;
if (t.size() == 1) {
temp = Integer.valueOf(t.get(0));
} else {
for (int j = t.size() - 1; j > 0; j = j - 2) {
if (t.get(j - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(j));
} else {
temp += Integer.valueOf(t.get(j));
}
}
temp += Integer.valueOf(t.get(0));
}
stack.push(String.valueOf(temp));
}
}
}

ArrayList<String> t = new ArrayList<String>();


while (!stack.isEmpty()) {
String elem = stack.pop();
t.add(0, elem);
}

int temp = 0;
for (int i = t.size() - 1; i > 0; i = i - 2) {
if (t.get(i - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(i));
} else {
temp += Integer.valueOf(t.get(i));
}
}
temp += Integer.valueOf(t.get(0));

return temp;
}

158 | 531 Program Creek

152 of
130 of 246
288
63 Group Anagrams

Given an array of strings, return all groups of strings that are anagrams.

63.1 Analysis

An anagram is a type of word play, the result of rearranging the letters of a word or
phrase to produce a new word or phrase, using all the original letters exactly once; for
example Torchwood can be rearranged into Doctor Who.
If two strings are anagram to each other, their sorted sequence is the same.
Updated on 5/1/2016.

63.2 Java Solution

public List<List<String>> groupAnagrams(String[] strs) {


List<List<String>> result = new ArrayList<List<String>>();

HashMap<String, ArrayList<String>> map = new HashMap<String,


ArrayList<String>>();
for(String str: strs){
char[] arr = str.toCharArray();
Arrays.sort(arr);
String ns = new String(arr);

if(map.containsKey(ns)){
map.get(ns).add(str);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(str);
map.put(ns, al);
}
}

for(Map.Entry<String, ArrayList<String>> entry: map.entrySet()){


Collections.sort(entry.getValue());
}

result.addAll(map.values());

return result;
}

159 | 531

153 of
131 of 246
288
63 Group Anagrams

63.3 Time Complexity

If average length of verbs is m and words array length is n, then the time is O(n*m*log(m)).

160 | 531 Program Creek

154 of
132 of 246
288
64 Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in


front of it. Find and return the shortest palindrome you can find by performing this
transformation.
For example, given "aacecaaa", return "aaacecaaa"; given "abcd", return "dcbabcd".

64.1 Analysis

We can solve this problem by using one of the methods which is used to solve the
longest palindrome substring problem.
Specifically, we can start from the center and scan two sides. If read the left bound-
ary, then the shortest palindrome is identified.

64.2 Java Solution

public String shortestPalindrome(String s) {


if (s == null || s.length() <= 1)
return s;

String result = null;

int len = s.length();


int mid = len / 2;

for (int i = mid; i >= 1; i--) {


if (s.charAt(i) == s.charAt(i - 1)) {
if ((result = scanFromCenter(s, i - 1, i)) != null)
return result;
} else {
if ((result = scanFromCenter(s, i - 1, i - 1)) != null)
return result;
}
}

return result;
}

private String scanFromCenter(String s, int l, int r) {


int i = 1;

161 | 531

155 of
133 of 246
288
64 Shortest Palindrome

//scan from center to both sides


for (; l - i >= 0; i++) {
if (s.charAt(l - i) != s.charAt(r + i))
break;
}

//if not end at the beginning of s, return null


if (l - i >= 0)
return null;

StringBuilder sb = new StringBuilder(s.substring(r + i));


sb.reverse();

return sb.append(s).toString();
}

162 | 531 Program Creek

156 of
134 of 246
288
65 Rectangle Area

Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle
is defined by its bottom left corner and top right corner coordinates.

65.1 Analysis

This problem can be converted as a overlap internal problem. On the x-axis, there are
(A,C) and (E,G); on the y-axis, there are (F,H) and (B,D). If they do not have overlap,
the total area is the sum of 2 rectangle areas. If they have overlap, the total area should
minus the overlap area.

65.2 Java Solution

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int
H) {
if(C<E||G<A )
return (G-E)*(H-F) + (C-A)*(D-B);

if(D<F || H<B)
return (G-E)*(H-F) + (C-A)*(D-B);

int right = Math.min(C,G);


int left = Math.max(A,E);
int top = Math.min(H,D);
int bottom = Math.max(F,B);

return (G-E)*(H-F) + (C-A)*(D-B) - (right-left)*(top-bottom);


}

163 | 531

157 of
135 of 246
288
66 Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges for
consecutive numbers.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

66.1 Analysis

66.2 Java Solution

public List<String> summaryRanges(int[] nums) {


List<String> result = new ArrayList<String>();

if(nums == null || nums.length==0)


return result;

if(nums.length==1){
result.add(nums[0]+"");
}

int pre = nums[0]; // previous element


int first = pre; // first element of each range

for(int i=1; i<nums.length; i++){


if(nums[i]==pre+1){
if(i==nums.length-1){
result.add(first+"->"+nums[i]);
}
}else{
if(first == pre){
result.add(first+"");
}else{
result.add(first + "->"+pre);
}

if(i==nums.length-1){
result.add(nums[i]+"");
}

first = nums[i];
}

165 | 531

159 of
136 of 246
288
66 Summary Ranges

pre = nums[i];
}

return result;
}

166 | 531 Program Creek

160 of
137 of 246
288
67 Increasing Triplet Subsequence

Given an unsorted array return whether an increasing subsequence of length 3 exists


or not in the array.
Examples: Given [1, 2, 3, 4, 5], return true.
Given [5, 4, 3, 2, 1], return false.

67.1 Analysis

This problem can be converted to be finding if there is a sequence such that the_smallest_so_far
<the_second_smallest_so_far <current. We use x, y and z to denote the 3 number re-
spectively.

67.2 Java Solution

public boolean increasingTriplet(int[] nums) {


int x = Integer.MAX_VALUE;
int y = Integer.MAX_VALUE;

for (int i = 0; i < nums.length; i++) {


int z = nums[i];

if (x >= z) {
x = z;// update x to be a smaller value
} else if (y >= z) {
y = z; // update y to be a smaller value
} else {
return true;
}
}

return false;
}

167 | 531

161 of
138 of 246
288
68 Get Target Number Using Number List
and Arithmetic Operations

Given a list of numbers and a target number, write a program to determine whether
the target number can be calculated by applying "+-*/" operations to the number list?
You can assume () is automatically added when necessary.
For example, given 1,2,3,4 and 21, return true. Because (1+2)*(3+4)=21

68.1 Analysis

This is a partition problem which can be solved by using depth first search.

68.2 Java Solution

public static boolean isReachable(ArrayList<Integer> list, int target) {


if (list == null || list.size() == 0)
return false;

int i = 0;
int j = list.size() - 1;

ArrayList<Integer> results = getResults(list, i, j, target);

for (int num : results) {


if (num == target) {
return true;
}
}

return false;
}

public static ArrayList<Integer> getResults(ArrayList<Integer> list,


int left, int right, int target) {
ArrayList<Integer> result = new ArrayList<Integer>();

if (left > right) {


return result;
} else if (left == right) {
result.add(list.get(left));

169 | 531

163 of
139 of 246
288
68 Get Target Number Using Number List and Arithmetic Operations

return result;
}

for (int i = left; i < right; i++) {

ArrayList<Integer> result1 = getResults(list, left, i, target);


ArrayList<Integer> result2 = getResults(list, i + 1, right, target);

for (int x : result1) {


for (int y : result2) {
result.add(x + y);
result.add(x - y);
result.add(x * y);
if (y != 0)
result.add(x / y);
}
}
}

return result;
}

170 | 531 Program Creek

164 of
140 of 246
288
69 Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

69.1 Java Solution

this is a simple problem which can be solved by using two pointers scanning from
beginning and end of the array.
public String reverseVowels(String s) {
ArrayList<Character> vowList = new ArrayList<Character>();
vowList.add(’a’);
vowList.add(’e’);
vowList.add(’i’);
vowList.add(’o’);
vowList.add(’u’);
vowList.add(’A’);
vowList.add(’E’);
vowList.add(’I’);
vowList.add(’O’);
vowList.add(’U’);

char[] arr = s.toCharArray();

int i=0;
int j=s.length()-1;

while(i<j){
if(!vowList.contains(arr[i])){
i++;
continue;
}

if(!vowList.contains(arr[j])){
j--;
continue;
}

char t = arr[i];
arr[i]=arr[j];
arr[j]=t;

i++;
j--;

171 | 531

165 of
141 of 246
288
69 Reverse Vowels of a String

return new String(arr);


}

172 | 531 Program Creek

166 of
142 of 246
288
70 Flip Game

You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid move.

70.1 Java Solution

public List<String> generatePossibleNextMoves(String s) {


List<String> result = new ArrayList<String>();

if(s==null)
return result;

char[] arr = s.toCharArray();


for(int i=0; i<arr.length-1; i++){
if(arr[i]==arr[i+1] && arr[i]==’+’){
arr[i]=’-’;
arr[i+1]=’-’;
result.add(new String(arr));
arr[i]=’+’;
arr[i+1]=’+’;
}
}

return result;
}

173 | 531

167 of
143 of 246
288
71 Flip Game II

You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++", return true. The starting player can guarantee a win
by flipping the middle "++" to become "+–+".

71.1 Java Solution

This problem is solved by backtracking.


public boolean canWin(String s) {
if(s==null||s.length()==0){
return false;
}

return canWinHelper(s.toCharArray());
}

public boolean canWinHelper(char[] arr){


for(int i=0; i<arr.length-1;i++){
if(arr[i]==’+’&&arr[i+1]==’+’){
arr[i]=’-’;
arr[i+1]=’-’;

boolean win = canWinHelper(arr);

arr[i]=’+’;
arr[i+1]=’+’;

//if there is a flip which makes the other player lose, the first
play wins
if(!win){
return true;
}
}
}

return false;
}

175 | 531

169 of
144 of 246
288
71 Flip Game II

71.2 Time Complexity

Roughly, the time is n*n*...n, which is O(nn̂). The reason is each recursion takes O(n)
and there are totally n recursions.

176 | 531 Program Creek

170 of
145 of 246
288
72 Move Zeroes

Given an array nums, write a function to move all 0’s to the end of it while maintaining
the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should
be [1, 3, 12, 0, 0].

72.1 Java Solution

public void moveZeroes(int[] nums) {


int m=-1;

for(int i=0; i<nums.length; i++){


if(nums[i]==0){
if(m==-1 || nums[m]!=0){
m=i;
}
}else{
if(m!=-1){
int temp = nums[i];
nums[i]=nums[m];
nums[m]=temp;
m++;
}
}
}
}

177 | 531

171 of
146 of 246
288
73 Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.

73.1 Java Solution 1

If the string contains only lowercase alphabets, here is a simple solution.


public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
return false;

int[] arr = new int[26];


for(int i=0; i<s.length(); i++){
char c1 = s.charAt(i);
arr[c1-’a’]++;
}

for(int i=0; i<s.length(); i++){


char c2 = t.charAt(i);
if(arr[c2-’a’] == 0){
return false;
}else{
arr[c2-’a’]--;
}
}

for(int i=0; i<26; i++){


if(arr[i]%2==1){
return false;
}
}

return true;
}

73.2 Java Solution 2

If the inputs contain unicode characters, an array with length of 26 is not enough.
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())

179 | 531

173 of
147 of 246
288
73 Valid Anagram

return false;

HashMap<Character, Integer> map = new HashMap<Character, Integer>();

for(int i=0; i<s.length(); i++){


char c1 = s.charAt(i);
if(map.containsKey(c1)){
map.put(c1, map.get(c1)+1);
}else{
map.put(c1,1);
}
}

for(int i=0; i<s.length(); i++){


char c2 = t.charAt(i);
if(map.containsKey(c2)){
if(map.get(c2)==1){
map.remove(c2);
}else{
map.put(c2, map.get(c2)-1);
}
}else{
return false;
}
}

if(map.size()>0)
return false;

return true;
}

180 | 531 Program Creek

174 of
148 of 246
288
74 Group Shifted Strings

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc"
->"bcd". We can keep "shifting" which forms the sequence: "abc" ->"bcd" ->... ->"xyz".
Given a list of strings which contains only lowercase alphabets, group all strings
that belong to the same shifting sequence, return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]

74.1 Java Solution

public List<List<String>> groupStrings(String[] strings) {


List<List<String>> result = new ArrayList<List<String>>();
HashMap<String, ArrayList<String>> map
= new HashMap<String, ArrayList<String>>();

for(String s: strings){
char[] arr = s.toCharArray();
if(arr.length>0){
int diff = arr[0]-’a’;
for(int i=0; i<arr.length; i++){
if(arr[i]-diff<’a’){
arr[i] = (char) (arr[i]-diff+26);
}else{
arr[i] = (char) (arr[i]-diff);
}

}
}

String ns = new String(arr);


if(map.containsKey(ns)){
map.get(ns).add(s);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(s);
map.put(ns, al);

181 | 531

175 of
149 of 246
288
74 Group Shifted Strings

}
}

for(Map.Entry<String, ArrayList<String>> entry: map.entrySet()){


Collections.sort(entry.getValue());
}

result.addAll(map.values());

return result;
}

182 | 531 Program Creek

176 of
150 of 246
288
75 Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

75.1 Java Solution

We can solve this problem by using a counter, and then sort the counter by value.
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> result = new ArrayList<Integer>();

HashMap<Integer, Integer> counter = new HashMap<Integer, Integer>();

for(int i: nums){
if(counter.containsKey(i)){
counter.put(i, counter.get(i)+1);
}else{
counter.put(i, 1);
}
}

TreeMap<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(new


ValueComparator(counter));
sortedMap.putAll(counter);

int i=0;
for(Map.Entry<Integer, Integer> entry: sortedMap.entrySet()){
result.add(entry.getKey());
i++;
if(i==k)
break;
}

return result;
}
}

class ValueComparator implements Comparator<Integer>{


HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

public ValueComparator(HashMap<Integer, Integer> m){


map.putAll(m);
}

183 | 531

177 of
151 of 246
288
75 Top K Frequent Elements

public int compare(Integer i1, Integer i2){


int diff = map.get(i2)-map.get(i1);

if(diff==0){
return 1;
}else{
return diff;
}
}
}

184 | 531 Program Creek

178 of
152 of 246
288
76 Find Peak Element

A peak element is an element that is greater than its neighbors. Given an input array
where num[i] %= num[i+1], find a peak element and return its index. The array may
contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞. For example, in array [1, 2, 3, 1], 3 is
a peak element and your function should return the index number 2.

76.1 Thoughts

This is a very simple problem. We can scan the array and find any element that is
greater can its previous and next. The first and last element are handled separately.

76.2 Java Solution

public class Solution {


public int findPeakElement(int[] num) {
int max = num[0];
int index = 0;
for(int i=1; i<=num.length-2; i++){
int prev = num[i-1];
int curr = num[i];
int next = num[i+1];

if(curr > prev && curr > next && curr > max){
index = i;
max = curr;
}
}

if(num[num.length-1] > max){


return num.length-1;
}

return index;
}
}

185 | 531

179 of
153 of 246
288
77 Word Pattern

Given a pattern and a string str, find if str follows the same pattern. Here follow means
a full match, such that there is a bijection between a letter in pattern and a non-empty
word in str.

77.1 Java Solution

public boolean wordPattern(String pattern, String str) {


String[] arr = str.split(" ");

if(pattern.length()!=arr.length)
return false;

HashMap<Character, String> map = new HashMap<Character, String>();

for(int i=0; i<arr.length; i++){


char c = pattern.charAt(i);
String s = arr[i];

if(map.containsKey(c)){
if(!map.get(c).equals(s))
return false;

}else{
if(map.containsValue(s))
return false;

map.put(c, s);
}
}

return true;
}

187 | 531

181 of
154 of 246
288
78 Set Matrix Zeroes

Given a m * n matrix, if an element is 0, set its entire row and column to 0. Do it in


place.

78.1 Analysis

This problem should be solved in place, i.e., no other array should be used. We can
use the first column and the first row to track if a row/column should be set to 0.
Since we used the first row and first column to mark the zero row/column, the
original values are changed.

Step 1: First row contains zero = true; First column contains zero = false;

189 | 531

183 of
155 of 246
288
78 Set Matrix Zeroes

78.2 Java Solution

public class Solution {


public void setZeroes(int[][] matrix) {
boolean firstRowZero = false;
boolean firstColumnZero = false;

//set first row and column zero or not


for(int i=0; i<matrix.length; i++){
if(matrix[i][0] == 0){
firstColumnZero = true;
break;
}
}

for(int i=0; i<matrix[0].length; i++){


if(matrix[0][i] == 0){
firstRowZero = true;
break;
}
}

190 | 531 Program Creek

184 of
156 of 246
288
78 Set Matrix Zeroes

//mark zeros on first row and column


for(int i=1; i<matrix.length; i++){
for(int j=1; j<matrix[0].length; j++){
if(matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

//use mark to set elements


for(int i=1; i<matrix.length; i++){
for(int j=1; j<matrix[0].length; j++){
if(matrix[i][0] == 0 || matrix[0][j] == 0){
matrix[i][j] = 0;
}
}
}

//set first column and row


if(firstColumnZero){
for(int i=0; i<matrix.length; i++)
matrix[i][0] = 0;
}

if(firstRowZero){
for(int i=0; i<matrix[0].length; i++)
matrix[0][i] = 0;
}

}
}

Program Creek 191 | 531

185 of
157 of 246
288
79 Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the


matrix in spiral order.
For example, given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

79.1 Java Solution 1

If more than one row and column left, it can form a circle and we process the circle.
Otherwise, if only one row or column left, we process that column or row ONLY.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();

if(matrix == null || matrix.length == 0) return result;

int m = matrix.length;
int n = matrix[0].length;

int x=0;
int y=0;

while(m>0 && n>0){

//if one row/column left, no circle can be formed


if(m==1){
for(int i=0; i<n; i++){
result.add(matrix[x][y++]);
}
break;
}else if(n==1){
for(int i=0; i<m; i++){
result.add(matrix[x++][y]);
}

193 | 531

187 of
158 of 246
288
79 Spiral Matrix

break;
}

//below, process a circle

//top - move right


for(int i=0;i<n-1;i++){
result.add(matrix[x][y++]);
}

//right - move down


for(int i=0;i<m-1;i++){
result.add(matrix[x++][y]);
}

//bottom - move left


for(int i=0;i<n-1;i++){
result.add(matrix[x][y--]);
}

//left - move up
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}

x++;
y++;
m=m-2;
n=n-2;
}

return result;
}
}

79.2 Java Solution 2

We can also recursively solve this problem. The solution’s performance is not better
than Solution or as clear as Solution 1. Therefore, Solution 1 should be preferred.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
if(matrix==null || matrix.length==0)
return new ArrayList<Integer>();

return spiralOrder(matrix,0,0,matrix.length,matrix[0].length);
}

194 | 531 Program Creek

188 of
159 of 246
288
79 Spiral Matrix

public ArrayList<Integer> spiralOrder(int [][] matrix, int x, int y, int


m, int n){
ArrayList<Integer> result = new ArrayList<Integer>();

if(m<=0||n<=0)
return result;

//only one element left


if(m==1&&n==1) {
result.add(matrix[x][y]);
return result;
}

//top - move right


for(int i=0;i<n-1;i++){
result.add(matrix[x][y++]);
}

//right - move down


for(int i=0;i<m-1;i++){
result.add(matrix[x++][y]);
}

//bottom - move left


if(m>1){
for(int i=0;i<n-1;i++){
result.add(matrix[x][y--]);
}
}

//left - move up
if(n>1){
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}
}

if(m==1||n==1)
result.addAll(spiralOrder(matrix, x, y, 1, 1));
else
result.addAll(spiralOrder(matrix, x+1, y+1, m-2, n-2));

return result;
}
}

Program Creek 195 | 531

189 of
160 of 246
288
80 Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral
order. For example, given n = 4,
[
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]

80.1 Java Solution

public int[][] generateMatrix(int n) {


int total = n*n;
int[][] result= new int[n][n];

int x=0;
int y=0;
int step = 0;

for(int i=0;i<total;){
while(y+step<n){
i++;
result[x][y]=i;
y++;

}
y--;
x++;

while(x+step<n){
i++;
result[x][y]=i;
x++;
}
x--;
y--;

while(y>=0+step){
i++;

197 | 531

191 of
161 of 246
288
80 Spiral Matrix II

result[x][y]=i;
y--;
}
y++;
x--;
step++;

while(x>=0+step){
i++;
result[x][y]=i;
x--;
}
x++;
y++;
}

return result;
}

198 | 531 Program Creek

192 of
162 of 246
288
81 Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has properties:
1) Integers in each row are sorted from left to right. 2) The first integer of each row
is greater than the last integer of the previous row.
For example, consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

81.1 Java Solution

This is a typical problem of binary search.


You may try to solve this problem by finding the row first and then the column.
There is no need to do that. Because of the matrix’s special features, the matrix can be
considered as a sorted array. Your goal is to find one element in this sorted array by
using binary search.
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null || matrix.length==0 || matrix[0].length==0)
return false;

int m = matrix.length;
int n = matrix[0].length;

int start = 0;
int end = m*n-1;

while(start<=end){
int mid=(start+end)/2;
int midX=mid/n;
int midY=mid%n;

if(matrix[midX][midY]==target)
return true;

199 | 531

193 of
163 of 246
288
81 Search a 2D Matrix

if(matrix[midX][midY]<target){
start=mid+1;
}else{
end=mid-1;
}
}

return false;
}
}

200 | 531 Program Creek

194 of
164 of 246
288
82 Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in each
column are sorted in ascending from top to bottom.
For example, consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

82.1 Java Solution 1

In a naive approach, we can use the matrix boundary to reduce the search space. Here
is a simple recursive implementation.
public boolean searchMatrix(int[][] matrix, int target) {
int i1=0;
int i2=matrix.length-1;
int j1=0;
int j2=matrix[0].length-1;

return helper(matrix, i1, i2, j1, j2, target);


}

public boolean helper(int[][] matrix, int i1, int i2, int j1, int j2, int
target){

if(i1>i2||j1>j2)
return false;

for(int j=j1;j<=j2;j++){
if(target < matrix[i1][j]){
return helper(matrix, i1, i2, j1, j-1, target);
}else if(target == matrix[i1][j]){
return true;

201 | 531

195 of
165 of 246
288
82 Search a 2D Matrix II

}
}

for(int i=i1;i<=i2;i++){
if(target < matrix[i][j1]){
return helper(matrix, i1, i-1, j1, j2, target);
}else if(target == matrix[i][j1]){
return true;
}
}

for(int j=j1;j<=j2;j++){
if(target > matrix[i2][j]){
return helper(matrix, i1, i2, j+1, j2, target);
}else if(target == matrix[i2][j]){
return true;
}
}

for(int i=i1;i<=i2;i++){
if(target > matrix[i][j2]){
return helper(matrix, i1, i+1, j1, j2, target);
}else if(target == matrix[i][j2]){
return true;
}
}

return false;
}

82.2 Java Solution 2

Time Complexity: O(m + n)


public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length-1;
int n=matrix[0].length-1;

int i=m;
int j=0;

while(i>=0 && j<=n){


if(target < matrix[i][j]){
i--;
}else if(target > matrix[i][j]){
j++;
}else{
return true;

202 | 531 Program Creek

196 of
166 of 246
288
82 Search a 2D Matrix II

}
}

return false;
}

Program Creek 203 | 531

197 of
167 of 246
288
83 Rotate Image

You are given an n x n 2D matrix representing an image.


Rotate the image by 90 degrees (clockwise).
Follow up: Could you do this in-place?

83.1 Naive Solution

In the following solution, a new 2-dimension array is created to store the rotated
matrix, and the result is assigned to the matrix at the end. This is WRONG! Why?
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;

int m = matrix.length;

int[][] result = new int[m][m];

for(int i=0; i<m; i++){


for(int j=0; j<m; j++){
result[j][m-1-i] = matrix[i][j];
}
}

matrix = result;
}
}

The problem is that Java is pass by value not by refrence! "matrix" is just a reference
to a 2-dimension array. If "matrix" is assigned to a new 2-dimension array in the
method, the original array does not change. Therefore, there should be another loop
to assign each element to the array referenced by "matrix". Check out "Java pass by
value."
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;

int m = matrix.length;

205 | 531

199 of
168 of 246
288
83 Rotate Image

int[][] result = new int[m][m];

for(int i=0; i<m; i++){


for(int j=0; j<m; j++){
result[j][m-1-i] = matrix[i][j];
}
}

for(int i=0; i<m; i++){


for(int j=0; j<m; j++){
matrix[i][j] = result[i][j];
}
}
}
}

83.2 In-place Solution

By using the relation "matrix[i][j] = matrix[n-1-j][i]", we can loop through the matrix.
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = temp;
}
}
}

206 | 531 Program Creek

200 of
169 of 246
288
84 Valid Sudoku

Determine if a Sudoku is valid. The Sudoku board could be partially filled, where
empty cells are filled with the character ’.’.

84.1 Java Solution

public boolean isValidSudoku(char[][] board) {


if (board == null || board.length != 9 || board[0].length != 9)
return false;
// check each column
for (int i = 0; i < 9; i++) {
boolean[] m = new boolean[9];
for (int j = 0; j < 9; j++) {
if (board[i][j] != ’.’) {
if (m[(int) (board[i][j] - ’1’)]) {
return false;
}
m[(int) (board[i][j] - ’1’)] = true;
}
}
}

//check each row


for (int j = 0; j < 9; j++) {
boolean[] m = new boolean[9];
for (int i = 0; i < 9; i++) {

207 | 531

201 of
170 of 246
288
84 Valid Sudoku

if (board[i][j] != ’.’) {
if (m[(int) (board[i][j] - ’1’)]) {
return false;
}
m[(int) (board[i][j] - ’1’)] = true;
}
}
}

//check each 3*3 matrix


for (int block = 0; block < 9; block++) {
boolean[] m = new boolean[9];
for (int i = block / 3 * 3; i < block / 3 * 3 + 3; i++) {
for (int j = block % 3 * 3; j < block % 3 * 3 + 3; j++) {
if (board[i][j] != ’.’) {
if (m[(int) (board[i][j] - ’1’)]) {
return false;
}
m[(int) (board[i][j] - ’1’)] = true;
}
}
}
}

return true;
}

208 | 531 Program Creek

202 of
171 of 246
288
85 Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to
bottom right which minimizes the sum of all numbers along its path.

85.1 Java Solution 1: Depth-First Search

A native solution would be depth-first search. It’s time is too expensive and fails the
online judgement.
public int minPathSum(int[][] grid) {
return dfs(0,0,grid);
}

public int dfs(int i, int j, int[][] grid){


if(i==grid.length-1 && j==grid[0].length-1){
return grid[i][j];
}

if(i<grid.length-1 && j<grid[0].length-1){


int r1 = grid[i][j] + dfs(i+1, j, grid);
int r2 = grid[i][j] + dfs(i, j+1, grid);
return Math.min(r1,r2);
}

if(i<grid.length-1){
return grid[i][j] + dfs(i+1, j, grid);
}

if(j<grid[0].length-1){
return grid[i][j] + dfs(i, j+1, grid);
}

return 0;
}

85.2 Java Solution 2: Dynamic Programming

public int minPathSum(int[][] grid) {


if(grid == null || grid.length==0)
return 0;

209 | 531

203 of
172 of 246
288
85 Minimum Path Sum

int m = grid.length;
int n = grid[0].length;

int[][] dp = new int[m][n];


dp[0][0] = grid[0][0];

// initialize top row


for(int i=1; i<n; i++){
dp[0][i] = dp[0][i-1] + grid[0][i];
}

// initialize left column


for(int j=1; j<m; j++){
dp[j][0] = dp[j-1][0] + grid[j][0];
}

// fill up the dp table


for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(dp[i-1][j] > dp[i][j-1]){
dp[i][j] = dp[i][j-1] + grid[i][j];
}else{
dp[i][j] = dp[i-1][j] + grid[i][j];
}
}
}

return dp[m-1][n-1];
}

210 | 531 Program Creek

204 of
173 of 246
288
86 Unique Paths

A robot is located at the top-left corner of a m x n grid. It can only move either down
or right at any point in time. The robot is trying to reach the bottom-right corner of
the grid.
How many possible unique paths are there?

86.1 Java Solution 1 - DFS

A depth-first search solution is pretty straight-forward. However, the time of this


solution is too expensive, and it didn’t pass the online judge.
public int uniquePaths(int m, int n) {
return dfs(0,0,m,n);
}

public int dfs(int i, int j, int m, int n){


if(i==m-1 && j==n-1){
return 1;
}

if(i<m-1 && j<n-1){


return dfs(i+1,j,m,n) + dfs(i,j+1,m,n);
}

if(i<m-1){
return dfs(i+1,j,m,n);
}

if(j<n-1){
return dfs(i,j+1,m,n);
}

return 0;
}

86.2 Java Solution 2 - Dynamic Programming

public int uniquePaths(int m, int n) {


if(m==0 || n==0) return 0;
if(m==1 || n==1) return 1;

211 | 531

205 of
174 of 246
288
86 Unique Paths

int[][] dp = new int[m][n];

//left column
for(int i=0; i<m; i++){
dp[i][0] = 1;
}

//top row
for(int j=0; j<n; j++){
dp[0][j] = 1;
}

//fill up the dp table


for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}

return dp[m-1][n-1];
}

212 | 531 Program Creek

206 of
175 of 246
288
87 Unique Paths II

Follow up for "Unique Paths":


Now consider if some obstacles are added to the grids. How many unique paths
would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid. For
example, there is one obstacle in the middle of a 3x3 grid as illustrated below,
[
[0,0,0],
[0,1,0],
[0,0,0]
]

the total number of unique paths is 2.

87.1 Java Solution

public int uniquePathsWithObstacles(int[][] obstacleGrid) {


if(obstacleGrid==null||obstacleGrid.length==0)
return 0;

int m = obstacleGrid.length;
int n = obstacleGrid[0].length;

if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1)
return 0;

int[][] dp = new int[m][n];


dp[0][0]=1;

//left column
for(int i=1; i<m; i++){
if(obstacleGrid[i][0]==1){
dp[i][0] = 0;
}else{
dp[i][0] = dp[i-1][0];
}
}

//top row

213 | 531

207 of
176 of 246
288
87 Unique Paths II

for(int i=1; i<n; i++){


if(obstacleGrid[0][i]==1){
dp[0][i] = 0;
}else{
dp[0][i] = dp[0][i-1];
}
}

//fill up cells inside


for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
if(obstacleGrid[i][j]==1){
dp[i][j]=0;
}else{
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}

}
}

return dp[m-1][n-1];
}

214 | 531 Program Creek

208 of
177 of 246
288
88 Number of Islands

Given a 2-d grid map of ’1’s (land) and ’0’s (water), count the number of islands. An
island is surrounded by water and is formed by connecting adjacent lands horizontally
or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000

Answer: 1
Example 2:
11000
11000
00100
00011

Answer: 3

88.1 Java Solution

The basic idea of the following solution is merging adjacent lands, and the merging
should be done recursively.
public int numIslands(char[][] grid) {
if(grid==null||grid.length==0||grid[0].length==0)
return 0;

int m=grid.length;
int n=grid[0].length;

int count=0;
for(int i=0;i<m; i++){
for(int j=0;j<n; j++){
if(grid[i][j]==’1’){
count++;
merge(grid, i, j);
}
}
}

215 | 531

209 of
178 of 246
288
88 Number of Islands

return count;
}

public void merge(char[][] grid, int i, int j){


if(i<0||j<0||i>=grid.length||j>=grid[0].length)
return;

if(grid[i][j]==’1’){
grid[i][j]=’0’;

merge(grid, i-1,j);
merge(grid, i+1,j);
merge(grid, i,j-1);
merge(grid, i,j+1);
}
}

Check out Number of Island II.

216 | 531 Program Creek

210 of
179 of 246
288
89 Number of Islands II

A 2d grid map of m rows and n columns is initially filled with water. We may perform
an addLand operation which turns the water at position (row, col) into a land. Given a
list of positions to operate, count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connecting adjacent lands hori-
zontally or vertically. You may assume all four edges of the grid are all surrounded by
water.

89.1 Java Solution

Use an array to track the parent node for each cell.


public List<Integer> numIslands2(int m, int n, int[][] positions) {
int[] rootArray = new int[m*n];
Arrays.fill(rootArray,-1);

ArrayList<Integer> result = new ArrayList<Integer>();

int[][] directions = {{-1,0},{0,1},{1,0},{0,-1}};


int count=0;

for(int k=0; k<positions.length; k++){


count++;

int[] p = positions[k];
int index = p[0]*n+p[1];
rootArray[index]=index;//set root to be itself for each node

for(int r=0;r<4;r++){
int i=p[0]+directions[r][0];
int j=p[1]+directions[r][1];

if(i>=0&&j>=0&&i<m&&j<n&&rootArray[i*n+j]!=-1){
//get neighbor’s root
int thisRoot = getRoot(rootArray, i*n+j);
if(thisRoot!=index){
rootArray[thisRoot]=index;//set previous root’s root
count--;
}
}
}

217 | 531

211 of
180 of 246
288
89 Number of Islands II

result.add(count);
}

return result;
}

public int getRoot(int[] arr, int i){


while(i!=arr[i]){
i=arr[arr[i]];
}
return i;
}

218 | 531 Program Creek

212 of
181 of 246
288
90 Surrounded Regions

Given a 2D board containing ’X’ and ’O’, capture all regions surrounded by ’X’. A
region is captured by flipping all ’O’s into ’X’s in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:


X X X X
X X X X
X X X X
X O X X

90.1 Analysis

This problem is similar to Number of Islands. In this problem, only the cells on the
boarders can not be surrounded. So we can first merge those O’s on the boarders like
in Number of Islands and replace O’s with ’#’, and then scan the board and replace all
O’s left (if any).

90.2 Depth-first Search

public void solve(char[][] board) {


if(board == null || board.length==0)
return;

int m = board.length;
int n = board[0].length;

//merge O’s on left & right boarder


for(int i=0;i<m;i++){
if(board[i][0] == ’O’){
merge(board, i, 0);
}

if(board[i][n-1] == ’O’){

219 | 531

213 of
182 of 246
288
90 Surrounded Regions

merge(board, i,n-1);
}
}

//merge O’s on top & bottom boarder


for(int j=0; j<n; j++){
if(board[0][j] == ’O’){
merge(board, 0,j);
}

if(board[m-1][j] == ’O’){
merge(board, m-1,j);
}
}

//process the board


for(int i=0;i<m;i++){
for(int j=0; j<n; j++){
if(board[i][j] == ’O’){
board[i][j] = ’X’;
}else if(board[i][j] == ’#’){
board[i][j] = ’O’;
}
}
}
}

public void merge(char[][] board, int i, int j){


if(i<0 || i>=board.length || j<0 || j>=board[0].length)
return;

if(board[i][j] != ’O’)
return;

board[i][j] = ’#’;

merge(board, i-1, j);


merge(board, i+1, j);
merge(board, i, j-1);
merge(board, i, j+1);
}

This solution causes java.lang.StackOverflowError, because for a large board, too


many method calls are pushed to the stack and causes the overflow.

90.3 Breath-first Search

Instead we use a queue to do breath-first search.

220 | 531 Program Creek

214 of
183 of 246
288
90 Surrounded Regions

public class Solution {


// use a queue to do BFS
private Queue<Integer> queue = new LinkedList<Integer>();

public void solve(char[][] board) {


if (board == null || board.length == 0)
return;

int m = board.length;
int n = board[0].length;

// merge O’s on left & right boarder


for (int i = 0; i < m; i++) {
if (board[i][0] == ’O’) {
bfs(board, i, 0);
}

if (board[i][n - 1] == ’O’) {
bfs(board, i, n - 1);
}
}

// merge O’s on top & bottom boarder


for (int j = 0; j < n; j++) {
if (board[0][j] == ’O’) {
bfs(board, 0, j);
}

if (board[m - 1][j] == ’O’) {


bfs(board, m - 1, j);
}
}

// process the board


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == ’O’) {
board[i][j] = ’X’;
} else if (board[i][j] == ’#’) {
board[i][j] = ’O’;
}
}
}
}

private void bfs(char[][] board, int i, int j) {


int n = board[0].length;

// fill current first and then its neighbors


fillCell(board, i, j);

Program Creek 221 | 531

215 of
184 of 246
288
90 Surrounded Regions

while (!queue.isEmpty()) {
int cur = queue.poll();
int x = cur / n;
int y = cur % n;

fillCell(board, x - 1, y);
fillCell(board, x + 1, y);
fillCell(board, x, y - 1);
fillCell(board, x, y + 1);
}
}

private void fillCell(char[][] board, int i, int j) {


int m = board.length;
int n = board[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != ’O’)
return;

// add current cell is queue & then process its neighbors in bfs
queue.offer(i * n + j);
board[i][j] = ’#’;
}
}

222 | 531 Program Creek

216 of
185 of 246
288
91 Maximal Rectangle

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing
all ones and return its area.

91.1 Analysis

This problem can be converted to the "Largest Rectangle in Histogram" problem.

91.2 Java Solution

public int maximalRectangle(char[][] matrix) {


int m = matrix.length;
int n = m == 0 ? 0 : matrix[0].length;
int[][] height = new int[m][n + 1];

int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == ’0’) {
height[i][j] = 0;
} else {
height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
}
}
}

for (int i = 0; i < m; i++) {


int area = maxAreaInHist(height[i]);
if (area > maxArea) {
maxArea = area;
}
}

return maxArea;
}

private int maxAreaInHist(int[] height) {


Stack<Integer> stack = new Stack<Integer>();

int i = 0;
int max = 0;

223 | 531

217 of
186 of 246
288
91 Maximal Rectangle

while (i < height.length) {


if (stack.isEmpty() || height[stack.peek()] <= height[i]) {
stack.push(i++);
} else {
int t = stack.pop();
max = Math.max(max, height[t]
* (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}

return max;
}

224 | 531 Program Creek

218 of
187 of 246
288
92 Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all
1’s and return its area.
For example, given the following matrix:
1101
1101
1111

Return 4.

92.1 Analysis

This problem can be solved by dynamic programming. The changing condition is:
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this
point.

92.2 Java Solution

public int maximalSquare(char[][] matrix) {


if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;

int m = matrix.length;
int n = matrix[0].length;

int[][] t = new int[m][n];

//top row
for (int i = 0; i < m; i++) {
t[i][0] = Character.getNumericValue(matrix[i][0]);
}

//left column
for (int j = 0; j < n; j++) {
t[0][j] = Character.getNumericValue(matrix[0][j]);
}

//cells inside
for (int i = 1; i < m; i++) {

225 | 531

219 of
188 of 246
288
92 Maximal Square

for (int j = 1; j < n; j++) {


if (matrix[i][j] == ’1’) {
int min = Math.min(t[i - 1][j], t[i - 1][j - 1]);
min = Math.min(min,t[i][j - 1]);
t[i][j] = min + 1;
} else {
t[i][j] = 0;
}
}
}

int max = 0;
//get maximal length
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (t[i][j] > max) {
max = t[i][j];
}
}
}

return max * max;


}

226 | 531 Program Creek

220 of
189 of 246
288
93 Word Search

Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "ad-
jacent" cells are those horizontally or vertically neighboring. The same letter cell may
not be used more than once.
For example, given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]

word = "ABCCED", ->returns true, word = "SEE", ->returns true, word = "ABCB",
->returns false.

93.1 Analysis

This problem can be solve by using a typical DFS method.

93.2 Java Solution

public boolean exist(char[][] board, String word) {


int m = board.length;
int n = board[0].length;

boolean result = false;


for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(dfs(board,word,i,j,0)){
result = true;
}
}
}

return result;
}

public boolean dfs(char[][] board, String word, int i, int j, int k){
int m = board.length;

227 | 531

221 of
190 of 246
288
93 Word Search

int n = board[0].length;

if(i<0 || j<0 || i>=m || j>=n){


return false;
}

if(board[i][j] == word.charAt(k)){
char temp = board[i][j];
board[i][j]=’#’;
if(k==word.length()-1){
return true;
}else if(dfs(board, word, i-1, j, k+1)
||dfs(board, word, i+1, j, k+1)
||dfs(board, word, i, j-1, k+1)
||dfs(board, word, i, j+1, k+1)){
return true;
}
board[i][j]=temp;
}

return false;
}

228 | 531 Program Creek

222 of
191 of 246
288
94 Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same letter cell
may not be used more than once in a word.
For example, given words = ["oath","pea","eat","rain"] and board =
[
[’o’,’a’,’a’,’n’],
[’e’,’t’,’a’,’e’],
[’i’,’h’,’k’,’r’],
[’i’,’f’,’l’,’v’]
]

Return ["eat","oath"].

94.1 Java Solution 1

Similar to Word Search, this problem can be solved by DFS. However, this solution
exceeds time limit.
public List<String> findWords(char[][] board, String[] words) {
ArrayList<String> result = new ArrayList<String>();

int m = board.length;
int n = board[0].length;

for (String word : words) {


boolean flag = false;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
char[][] newBoard = new char[m][n];
for (int x = 0; x < m; x++)
for (int y = 0; y < n; y++)
newBoard[x][y] = board[x][y];

if (dfs(newBoard, word, i, j, 0)) {


flag = true;
}
}
}
if (flag) {

229 | 531

223 of
192 of 246
288
94 Word Search II

result.add(word);
}
}

return result;
}

public boolean dfs(char[][] board, String word, int i, int j, int k) {


int m = board.length;
int n = board[0].length;

if (i < 0 || j < 0 || i >= m || j >= n || k > word.length() - 1) {


return false;
}

if (board[i][j] == word.charAt(k)) {
char temp = board[i][j];
board[i][j] = ’#’;

if (k == word.length() - 1) {
return true;
} else if (dfs(board, word, i - 1, j, k + 1)
|| dfs(board, word, i + 1, j, k + 1)
|| dfs(board, word, i, j - 1, k + 1)
|| dfs(board, word, i, j + 1, k + 1)) {
board[i][j] = temp;
return true;
}

} else {
return false;
}

return false;
}

94.2 Java Solution 2 - Trie

If the current candidate does not exist in all words’ prefix, we can stop backtracking
immediately. This can be done by using a trie structure.
public class Solution {
Set<String> result = new HashSet<String>();

public List<String> findWords(char[][] board, String[] words) {


//HashSet<String> result = new HashSet<String>();

Trie trie = new Trie();

230 | 531 Program Creek

224 of
193 of 246
288
94 Word Search II

for(String word: words){


trie.insert(word);
}

int m=board.length;
int n=board[0].length;

boolean[][] visited = new boolean[m][n];

for(int i=0; i<m; i++){


for(int j=0; j<n; j++){
dfs(board, visited, "", i, j, trie);
}
}

return new ArrayList<String>(result);


}

public void dfs(char[][] board, boolean[][] visited, String str, int i,


int j, Trie trie){
int m=board.length;
int n=board[0].length;

if(i<0 || j<0||i>=m||j>=n){
return;
}

if(visited[i][j])
return;

str = str + board[i][j];

if(!trie.startsWith(str))
return;

if(trie.search(str)){
result.add(str);
}

visited[i][j]=true;
dfs(board, visited, str, i-1, j, trie);
dfs(board, visited, str, i+1, j, trie);
dfs(board, visited, str, i, j-1, trie);
dfs(board, visited, str, i, j+1, trie);
visited[i][j]=false;
}
}

//Trie Node

Program Creek 231 | 531

225 of
194 of 246
288
94 Word Search II

class TrieNode{
public TrieNode[] children = new TrieNode[26];
public String item = "";
}

//Trie
class Trie{
public TrieNode root = new TrieNode();

public void insert(String word){


TrieNode node = root;
for(char c: word.toCharArray()){
if(node.children[c-’a’]==null){
node.children[c-’a’]= new TrieNode();
}
node = node.children[c-’a’];
}
node.item = word;
}

public boolean search(String word){


TrieNode node = root;
for(char c: word.toCharArray()){
if(node.children[c-’a’]==null)
return false;
node = node.children[c-’a’];
}
if(node.item.equals(word)){
return true;
}else{
return false;
}
}

public boolean startsWith(String prefix){


TrieNode node = root;
for(char c: prefix.toCharArray()){
if(node.children[c-’a’]==null)
return false;
node = node.children[c-’a’];
}
return true;
}
}

232 | 531 Program Creek

226 of
195 of 246
288
95 Integer Break

Given a positive integer n, break it into the sum of at least two positive integers and
maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 +
4).

95.1 Java Solution 1 - Dynamic Programming

Let dp[i] to be the max production value for breaking the number i. Since dp[i+j] can
be i*j, dp[i+j] = max(max(dp[i], i) * max(dp[j], j)), dp[i+j]).
public int integerBreak(int n) {
int[] dp = new int[n+1];

for(int i=1; i<n; i++){


for(int j=1; j<i+1; j++){
if(i+j<=n){
dp[i+j]=Math.max(Math.max(dp[i],i)*Math.max(dp[j],j), dp[i+j]);
}
}
}

return dp[n];
}

95.2 Java Solution 2 - Using Regularities

If we see the breaking result for some numbers, we can see repeated pattern like the
following:
2 -> 1*1
3 -> 1*2
4 -> 2*2
5 -> 3*2
6 -> 3*3
7 -> 3*4
8 -> 3*3*2
9 -> 3*3*3
10 -> 3*3*4
11 -> 3*3*3*2

233 | 531

227 of
196 of 246
288
95 Integer Break

We only need to find how many 3’s we can get when n>4. If n
public int integerBreak(int n) {

if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;

int result=1;
if(n%3==0){
int m = n/3;
result = (int) Math.pow(3, m);
}else if(n%3==2){
int m=n/3;
result = (int) Math.pow(3, m) * 2;
}else if(n%3==1){
int m=(n-4)/3;
result = (int) Math.pow(3, m) *4;
}

return result;
}

234 | 531 Program Creek

228 of
197 of 246
288
96 Range Sum Query 2D Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined
by its upper left corner (row1, col1) and lower right corner (row2, col2).

96.1 Analysis

Since the assumption is that there are many calls to sumRegion method, we should
use some extra space to store the intermediate results. Here we define an array sum[][]
which stores the sum value from (0,0) to the current cell.

96.2 Java Solution

public class NumMatrix {


int [][] sum;

public NumMatrix(int[][] matrix) {


if(matrix==null || matrix.length==0||matrix[0].length==0)
return;

int m = matrix.length;
int n = matrix[0].length;
sum = new int[m][n];

for(int i=0; i<m; i++){


int sumRow=0;
for(int j=0; j<n; j++){
if(i==0){
sumRow += matrix[i][j];
sum[i][j]=sumRow;
}else{
sumRow += matrix[i][j];
sum[i][j]=sumRow+sum[i-1][j];
}

}
}
}

public int sumRegion(int row1, int col1, int row2, int col2) {
if(this.sum==null)

235 | 531

229 of
198 of 246
288
96 Range Sum Query 2D Immutable

return 0;

int topRightX = row1;


int topRightY = col2;

int bottomLeftX=row2;
int bottomLeftY= col1;

int result=0;

if(row1==0 && col1==0){


result = sum[row2][col2];
}else if(row1==0){
result = sum[row2][col2]
-sum[bottomLeftX][bottomLeftY-1];

}else if(col1==0){
result = sum[row2][col2]
-sum[topRightX-1][topRightY];
}else{
result = sum[row2][col2]
-sum[topRightX-1][topRightY]
-sum[bottomLeftX][bottomLeftY-1]
+sum[row1-1][col1-1];
}

return result;
}
}

236 | 531 Program Creek

230 of
199 of 246
288
97 Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You
may NOT move diagonally or move outside of the boundary

97.1 Java Solution 1 - DFS

This solution is over time limit.


public class Solution {
int longest=0;

public int longestIncreasingPath(int[][] matrix) {


if(matrix==null||matrix.length==0||matrix[0].length==0)
return 0;

for(int i=0; i<matrix.length; i++){


for(int j=0; j<matrix[0].length; j++){
helper(matrix, i, j, 1);
}
}

return longest;
}

public void helper(int[][] matrix, int i, int j, int len){

if(i-1>=0 && matrix[i-1][j]>matrix[i][j]){


longest = Math.max(longest, len+1);
helper(matrix, i-1, j, len+1);
}

if(i+1<matrix.length && matrix[i+1][j]>matrix[i][j]){


longest = Math.max(longest, len+1);
helper(matrix, i+1, j, len+1);
}

if(j-1>=0 && matrix[i][j-1]>matrix[i][j]){


longest = Math.max(longest, len+1);
helper(matrix, i, j-1, len+1);
}

237 | 531

231 of
200 of 246
288
97 Longest Increasing Path in a Matrix

if(j+1<matrix[0].length && matrix[i][j+1]>matrix[i][j]){


longest = Math.max(longest, len+1);
helper(matrix, i, j+1, len+1);
}

}
}

97.2 Java Solution - Optimized

public class Solution {


int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};

public int longestIncreasingPath(int[][] matrix) {


if(matrix==null||matrix.length==0||matrix[0].length==0)
return 0;

int[][] mem = new int[matrix.length][matrix[0].length];


int longest=0;

for(int i=0; i<matrix.length; i++){


for(int j=0; j<matrix[0].length; j++){
longest = Math.max(longest, dfs(matrix, i, j, mem));
}
}

return longest;
}

public int dfs(int[][] matrix, int i, int j, int[][] mem){


if(mem[i][j]!=0)
return mem[i][j];

for(int m=0; m<4; m++){


int x = i+dx[m];
int y = j+dy[m];

if(x>=0&&y>=0&&x<matrix.length&&y<matrix[0].length&&matrix[x][y]>matrix[i][j]){
mem[i][j]=Math.max(mem[i][j], dfs(matrix, x, y, mem));
}
}

return ++mem[i][j];
}
}

238 | 531 Program Creek

232 of
201 of 246
288
98 Implement a Stack Using an Array in
Java

This post shows how to implement a stack by using an array.


The requirements of the stack are: 1) the stack has a constructor which accept a
number to initialize its size, 2) the stack can hold any type of elements, 3) the stack
has a push() and a pop() method.
I remember there is a similar example in the "Effective Java" book written by Joshua
Bloch, but not sure how the example is used. So I just write one and then read the
book, and see if I miss anything.

98.1 A Simple Stack Implementation

public class Stack<E> {


private E[] arr = null;
private int CAP;
private int top = -1;
private int size = 0;

@SuppressWarnings("unchecked")
public Stack(int cap) {
this.CAP = cap;
this.arr = (E[]) new Object[cap];
}

public E pop() {
if(this.size == 0){
return null;
}

this.size--;
E result = this.arr[top];
this.arr[top] = null;//prevent memory leaking
this.top--;

return result;
}

public boolean push(E e) {


if (!isFull())
return false;

239 | 531

233 of
202 of 246
288
98 Implement a Stack Using an Array in Java

this.size++;
this.arr[++top] = e;
return false;
}

public boolean isFull() {


if (this.size == this.CAP)
return false;
return true;
}

public String toString() {


if(this.size==0){
return null;
}

StringBuilder sb = new StringBuilder();


for(int i=0; i<this.size; i++){
sb.append(this.arr[i] + ", ");
}

sb.setLength(sb.length()-2);
return sb.toString();
}

public static void main(String[] args) {

Stack<String> stack = new Stack<String>(11);


stack.push("hello");
stack.push("world");

System.out.println(stack);

stack.pop();
System.out.println(stack);

stack.pop();
System.out.println(stack);
}
}

Output:
hello, world
hello
null

240 | 531 Program Creek

234 of
203 of 246
288
98 Implement a Stack Using an Array in Java

98.2 Information from "Effective Java"

It turns out I don’t need to improve anything. There are some naming differences but
overall my method is ok.
This example occurs twice in "Effective Java". In the first place, the stack example is
used to illustrate memory leak. In the second place, the example is used to illustrate
when we can suppress unchecked warnings.
Do you wonder how to implement a queue by using an array?

Program Creek 241 | 531

235 of
204 of 246
288
99 Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are
stored in reverse order and each of their nodes contain a single digit. Add the two
numbers and return it as a linked list.
Input: (2 ->4 ->3) + (5 ->6 ->4) Output: 7 ->0 ->8

99.1 Java Solution

public class Solution {


public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry =0;

ListNode newHead = new ListNode(0);


ListNode p1 = l1, p2 = l2, p3=newHead;

while(p1 != null || p2 != null){


if(p1 != null){
carry += p1.val;
p1 = p1.next;
}

if(p2 != null){
carry += p2.val;
p2 = p2.next;
}

p3.next = new ListNode(carry%10);


p3 = p3.next;
carry /= 10;
}

if(carry==1)
p3.next=new ListNode(1);

return newHead.next;
}
}

What if the digits are stored in regular order instead of reversed order?
Answer: We can simple reverse the list, calculate the result, and reverse the result.

243 | 531

237 of
205 of 246
288
100 Reorder List

Given a singly linked list L: L0→L1→ ... →Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-
1→L2→Ln-2→...
For example, given 1,2,3,4, reorder it to 1,4,2,3. You must do this in-place without
altering the nodes’ values.

100.1 Analysis

This problem is not straightforward, because it requires "in-place" operations. That


means we can only change their pointers, not creating a new list.

100.2 Java Solution

This problem can be solved by doing the following:

• Break list in the middle to two lists (use fast & slow pointers)
• Reverse the order of the second list
• Merge two list back together

The following code is a complete runnable class with testing.


//Class definition of ListNode
class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
next = null;
}
}

public class ReorderList {

public static void main(String[] args) {


ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;
n2.next = n3;

245 | 531

239 of
206 of 246
288
100 Reorder List

n3.next = n4;

printList(n1);

reorderList(n1);

printList(n1);
}

public static void reorderList(ListNode head) {

if (head != null && head.next != null) {

ListNode slow = head;


ListNode fast = head;

//use a fast and slow pointer to break the link to two parts.
while (fast != null && fast.next != null && fast.next.next!= null) {
//why need third/second condition?
System.out.println("pre "+slow.val + " " + fast.val);
slow = slow.next;
fast = fast.next.next;
System.out.println("after " + slow.val + " " + fast.val);
}

ListNode second = slow.next;


slow.next = null;// need to close first part

// now should have two lists: head and fast

// reverse order for second part


second = reverseOrder(second);

ListNode p1 = head;
ListNode p2 = second;

//merge two lists here


while (p2 != null) {
ListNode temp1 = p1.next;
ListNode temp2 = p2.next;

p1.next = p2;
p2.next = temp1;

p1 = temp1;
p2 = temp2;
}
}
}

246 | 531 Program Creek

240 of
207 of 246
288
100 Reorder List

public static ListNode reverseOrder(ListNode head) {

if (head == null || head.next == null) {


return head;
}

ListNode pre = head;


ListNode curr = head.next;

while (curr != null) {


ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}

// set head node’s next


head.next = null;

return pre;
}

public static void printList(ListNode n) {


System.out.println("------");
while (n != null) {
System.out.print(n.val);
n = n.next;
}
System.out.println();
}
}

100.3 Takeaway Messages

The three steps can be used to solve other problems of linked list. A little diagram
may help better understand them.

Reverse List:

Program Creek 247 | 531

241 of
208 of 246
288
100 Reorder List

Merge List:

248 | 531 Program Creek

242 of
209 of 246
288
100 Reorder List

Program Creek 249 | 531

243 of
210 of 246
288
101 Linked List Cycle

Given a linked list, determine if it has a cycle in it.

101.1 Analysis

If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the
slow one if there exists a circle.

101.2 Java Solution

public class Solution {


public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;

while(fast != null && fast.next != null){


slow = slow.next;
fast = fast.next.next;

if(slow == fast)
return true;
}

return false;
}
}

251 | 531

245 of
211 of 246
288
102 Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which
could point to any node in the list or null.
Return a deep copy of the list.

102.1 Java Solution 1

We can solve this problem by doing the following steps:

• copy every node, i.e., duplicate every node, and insert it to the list
• copy random pointers for all newly created nodes
• break the list to two

public RandomListNode copyRandomList(RandomListNode head) {

if (head == null)
return null;

RandomListNode p = head;

// copy every node and insert to list


while (p != null) {
RandomListNode copy = new RandomListNode(p.label);
copy.next = p.next;
p.next = copy;
p = copy.next;
}

// copy random pointer for each new node


p = head;
while (p != null) {
if (p.random != null)
p.next.random = p.random.next;
p = p.next.next;
}

// break list to two


p = head;
RandomListNode newHead = head.next;
while (p != null) {
RandomListNode temp = p.next;

253 | 531

247 of
212 of 246
288
102 Copy List with Random Pointer

p.next = temp.next;
if (temp.next != null)
temp.next = temp.next.next;
p = p.next;
}

return newHead;
}

The break list part above move pointer 2 steps each time, you can also move one at
a time which is simpler, like the following:
while(p != null && p.next != null){
RandomListNode temp = p.next;
p.next = temp.next;
p = temp;
}

102.2 Java Solution 2 - Using HashMap

From Xiaomeng’s comment below, we can use a HashMap which makes it simpler.
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode,
RandomListNode>();
RandomListNode newHead = new RandomListNode(head.label);

RandomListNode p = head;
RandomListNode q = newHead;
map.put(head, newHead);

p = p.next;
while (p != null) {
RandomListNode temp = new RandomListNode(p.label);
map.put(p, temp);
q.next = temp;
q = temp;
p = p.next;
}

p = head;
q = newHead;
while (p != null) {
if (p.random != null)
q.random = map.get(p.random);
else

254 | 531 Program Creek

248 of
213 of 246
288
102 Copy List with Random Pointer

q.random = null;

p = p.next;
q = q.next;
}

return newHead;
}

Program Creek 255 | 531

249 of
214 of 246
288
103 Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made
by splicing together the nodes of the first two lists.

103.1 Analysis

The key to solve the problem is defining a fake head. Then compare the first elements
from each list. Add the smaller one to the merged list. Finally, when one of them is
empty, simply append it to the merged list, since it is already sorted.

103.2 Java Solution

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

ListNode p1 = l1;
ListNode p2 = l2;

ListNode fakeHead = new ListNode(0);


ListNode p = fakeHead;

while(p1 != null && p2 != null){


if(p1.val <= p2.val){
p.next = p1;
p1 = p1.next;
}else{
p.next = p2;
p2 = p2.next;
}

257 | 531

251 of
215 of 246
288
103 Merge Two Sorted Lists

p = p.next;
}

if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;

return fakeHead.next;
}
}

258 | 531 Program Creek

252 of
216 of 246
288
104 Odd Even Linked List

104.1 Problem

Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

104.2 Analysis

This problem can be solved by using two pointers. We iterate over the link and move
the two pointers.

104.3 Java Solution

public ListNode oddEvenList(ListNode head) {


if(head == null)
return head;

ListNode result = head;


ListNode p1 = head;
ListNode p2 = head.next;
ListNode connectNode = head.next;

259 | 531

253 of
217 of 246
288
104 Odd Even Linked List

while(p1 != null && p2 != null){


ListNode t = p2.next;
if(t == null)
break;

p1.next = p2.next;
p1 = p1.next;

p2.next = p1.next;
p2 = p2.next;
}

p1.next = connectNode;

return result;
}

260 | 531 Program Creek

254 of
218 of 246
288
105 Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only
once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

105.1 Thoughts

The key of this problem is using the right loop condition. And change what is nec-
essary in each loop. You can use different iteration conditions like the following 2
solutions.

105.2 Solution 1

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;

ListNode prev = head;


ListNode p = head.next;

while(p != null){
if(p.val == prev.val){
prev.next = p.next;
p = p.next;
//no change prev

261 | 531

255 of
219 of 246
288
105 Remove Duplicates from Sorted List

}else{
prev = p;
p = p.next;
}
}

return head;
}
}

105.3 Solution 2

public class Solution {


public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;

ListNode p = head;

while( p!= null && p.next != null){


if(p.val == p.next.val){
p.next = p.next.next;
}else{
p = p.next;
}
}

return head;
}
}

262 | 531 Program Creek

256 of
220 of 246
288
106 Remove Duplicates from Sorted List
II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only
distinct numbers from the original list.
For example, given 1->1->1->2->3, return 2->3.

106.1 Java Solution

public ListNode deleteDuplicates(ListNode head) {


ListNode t = new ListNode(0);
t.next = head;

ListNode p = t;
while(p.next!=null&&p.next.next!=null){
if(p.next.val == p.next.next.val){
int dup = p.next.val;
while(p.next!=null&&p.next.val==dup){
p.next = p.next.next;
}
}else{
p=p.next;
}

return t.next;
}

263 | 531

257 of
221 of 246
288
107 Partition List

Given a linked list and a value x, partition it such that all nodes less than x come
before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two
partitions.
For example, given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.

107.1 Java Solution

public class Solution {


public ListNode partition(ListNode head, int x) {
if(head == null) return null;

ListNode fakeHead1 = new ListNode(0);


ListNode fakeHead2 = new ListNode(0);
fakeHead1.next = head;

ListNode p = head;
ListNode prev = fakeHead1;
ListNode p2 = fakeHead2;

while(p != null){
if(p.val < x){
p = p.next;
prev = prev.next;
}else{

p2.next = p;
prev.next = p.next;

p = prev.next;
p2 = p2.next;
}
}

// close the list


p2.next = null;

prev.next = fakeHead2.next;

return fakeHead1.next;

265 | 531

259 of
222 of 246
288
107 Partition List

}
}

266 | 531 Program Creek

260 of
223 of 246
288
108 LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should
support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the
cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not
already present. When the cache reached its capacity, it should invalidate the least
recently used item before inserting a new item.

108.1 Analysis

The key to solve this problem is using a double linked list which enables us to quickly
move nodes.

The LRU cache is a hash table of keys and double linked nodes. The hash table
makes the time of get() to be O(1). The list of double linked nodes make the nodes
adding/removal operations O(1).

108.2 Java Solution

Define a double linked list node.


class Node{
int key;
int value;
Node pre;
Node next;

267 | 531

261 of
224 of 246
288
108 LRU Cache

public Node(int key, int value){


this.key = key;
this.value = value;
}
}

public class LRUCache {


int capacity;
HashMap<Integer, Node> map = new HashMap<Integer, Node>();
Node head=null;
Node end=null;

public LRUCache(int capacity) {


this.capacity = capacity;
}

public int get(int key) {


if(map.containsKey(key)){
Node n = map.get(key);
remove(n);
setHead(n);
return n.value;
}

return -1;
}

public void remove(Node n){


if(n.pre!=null){
n.pre.next = n.next;
}else{
head = n.next;
}

if(n.next!=null){
n.next.pre = n.pre;
}else{
end = n.pre;
}

public void setHead(Node n){


n.next = head;
n.pre = null;

if(head!=null)
head.pre = n;

268 | 531 Program Creek

262 of
225 of 246
288
108 LRU Cache

head = n;

if(end ==null)
end = head;
}

public void set(int key, int value) {


if(map.containsKey(key)){
Node old = map.get(key);
old.value = value;
remove(old);
setHead(old);
}else{
Node created = new Node(key, value);
if(map.size()>=capacity){
map.remove(end.key);
remove(end);
setHead(created);

}else{
setHead(created);
}

map.put(key, created);
}
}
}

Program Creek 269 | 531

263 of
226 of 246
288
109 Intersection of Two Linked Lists

109.1 Problem

Write a program to find the node at which the intersection of two singly linked lists
begins.
For example, the following two linked lists:
A: a1 -> a2
->
c1 -> c2 -> c3
->
B: b1 -> b2 -> b3

begin to intersect at node c1.

109.2 Java Solution

First calculate the length of two lists and find the difference. Then start from the longer
list at the diff offset, iterate though 2 lists and find the node.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int len1 = 0;
int len2 = 0;
ListNode p1=headA, p2=headB;
if (p1 == null || p2 == null)
return null;

while(p1 != null){
len1++;
p1 = p1.next;

271 | 531

265 of
227 of 246
288
109 Intersection of Two Linked Lists

}
while(p2 !=null){
len2++;
p2 = p2.next;
}

int diff = 0;
p1=headA;
p2=headB;

if(len1 > len2){


diff = len1-len2;
int i=0;
while(i<diff){
p1 = p1.next;
i++;
}
}else{
diff = len2-len1;
int i=0;
while(i<diff){
p2 = p2.next;
i++;
}
}

while(p1 != null && p2 != null){


if(p1.val == p2.val){
return p1;
}else{

}
p1 = p1.next;
p2 = p2.next;
}

return null;
}
}

272 | 531 Program Creek

266 of
228 of 246
288
110 Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

110.1 Java Solution

The key to solve this problem is using a helper node to track the head of the list.
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;

while(p.next != null){
if(p.next.val == val){
ListNode next = p.next;
p.next = next.next;
}else{
p = p.next;
}
}

return helper.next;
}

273 | 531

267 of
229 of 246
288
111 Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.
For example, given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in
the list, only nodes itself can be changed.

111.1 Java Solution

Use two template variable to track the previous and next node of each pair.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;

ListNode h = new ListNode(0);


h.next = head;
ListNode p = h;

while(p.next != null && p.next.next != null){


//use t1 to track first node
ListNode t1 = p;
p = p.next;
t1.next = p.next;

//use t2 to track next node of the pair


ListNode t2 = p.next.next;
p.next.next = p;
p.next = t2;
}

return h.next;
}

275 | 531

269 of
230 of 246
288
112 Reverse Linked List

Reverse a singly linked list.

112.1 Java Solution 1 - Iterative

public ListNode reverseList(ListNode head) {


if(head==null || head.next == null)
return head;

ListNode p1 = head;
ListNode p2 = head.next;

head.next = null;
while(p1!= null && p2!= null){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}

return p2;
}

112.2 Java Solution 2 - Recursive

public ListNode reverseList(ListNode head) {


if(head==null || head.next == null)
return head;

//get second node


ListNode second = head.next;
//set first’s next to be null
head.next = null;

ListNode rest = reverseList(second);

277 | 531

271 of
231 of 246
288
112 Reverse Linked List

second.next = head;

return rest;
}

278 | 531 Program Creek

272 of
232 of 246
288
113 Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.


For example: given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5-
>NULL.

113.1 Analysis

113.2 Java Solution

public ListNode reverseBetween(ListNode head, int m, int n) {


if(m==n) return head;

ListNode prev = null;//track (m-1)th node


ListNode first = new ListNode(0);//first’s next points to mth
ListNode second = new ListNode(0);//second’s next points to (n+1)th

int i=0;
ListNode p = head;
while(p!=null){
i++;
if(i==m-1){
prev = p;
}

if(i==m){
first.next = p;
}

if(i==n){
second.next = p.next;
p.next = null;
}

p= p.next;
}
if(first.next == null)
return head;

// reverse list [m, n]


ListNode p1 = first.next;
ListNode p2 = p1.next;

279 | 531

273 of
233 of 246
288
113 Reverse Linked List II

p1.next = second.next;

while(p1!=null && p2!=null){


ListNode t = p2.next;
p2.next = p1;
p1 = p2;
p2 = t;
}

//connect to previous part


if(prev!=null)
prev.next = p1;
else
return p1;

return head;
}

280 | 531 Program Creek

274 of
234 of 246
288
114 Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example, given linked list 1->2->3->4->5 and n = 2, the result is 1->2->3->5.

114.1 Java Solution 1 - Naive Two Passes

Calculate the length first, and then remove the nth from the beginning.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;

//get length of list


ListNode p = head;
int len = 0;
while(p != null){
len++;
p = p.next;
}

//if remove first node


int fromStart = len-n+1;
if(fromStart==1)
return head.next;

//remove non-first node


p = head;
int i=0;
while(p!=null){
i++;
if(i==fromStart-1){
p.next = p.next.next;
}
p=p.next;
}

return head;
}

281 | 531

275 of
235 of 246
288
114 Remove Nth Node From End of List

114.2 Java Solution 2 - One Pass

Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When
the fast reaches the end, the slow pointer points at the previous element of the target
element.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;

ListNode fast = head;


ListNode slow = head;

for(int i=0; i<n; i++){


fast = fast.next;
}

//if remove the first node


if(fast == null){
head = head.next;
return head;
}

while(fast.next != null){
fast = fast.next;
slow = slow.next;
}

slow.next = slow.next.next;

return head;
}

282 | 531 Program Creek

276 of
236 of 246
288
115 Implement Stack using Queues

Implement the following operations of a stack using queues. push(x) – Push element
x onto stack. pop() – Removes the element on top of the stack. top() – Get the top
element. empty() – Return whether the stack is empty.
Note: only standard queue operations are allowed, i.e., poll(), offer(), peek(), size()
and isEmpty() in Java.

115.1 Analysis

This problem can be solved by using two queues.

115.2 Java Solution

class MyStack {
LinkedList<Integer> queue1 = new LinkedList<Integer>();
LinkedList<Integer> queue2 = new LinkedList<Integer>();

// Push element x onto stack.


public void push(int x) {
if(empty()){
queue1.offer(x);
}else{
if(queue1.size()>0){
queue2.offer(x);
int size = queue1.size();
while(size>0){
queue2.offer(queue1.poll());
size--;
}
}else if(queue2.size()>0){
queue1.offer(x);
int size = queue2.size();
while(size>0){
queue1.offer(queue2.poll());
size--;
}
}
}
}

283 | 531

277 of
237 of 246
288
115 Implement Stack using Queues

// Removes the element on top of the stack.


public void pop() {
if(queue1.size()>0){
queue1.poll();
}else if(queue2.size()>0){
queue2.poll();
}
}

// Get the top element.


public int top() {
if(queue1.size()>0){
return queue1.peek();
}else if(queue2.size()>0){
return queue2.peek();
}
return 0;
}

// Return whether the stack is empty.


public boolean empty() {
return queue1.isEmpty() & queue2.isEmpty();
}
}

284 | 531 Program Creek

278 of
238 of 246
288
116 Implement Queue using Stacks

Implement the following operations of a queue using stacks.


push(x) – Push element x to the back of queue. pop() – Removes the element from
in front of queue. peek() – Get the front element. empty() – Return whether the queue
is empty.

116.1 Java Solution

class MyQueue {

Stack<Integer> temp = new Stack<Integer>();


Stack<Integer> value = new Stack<Integer>();

// Push element x to the back of queue.


public void push(int x) {
if(value.isEmpty()){
value.push(x);
}else{
while(!value.isEmpty()){
temp.push(value.pop());
}

value.push(x);

while(!temp.isEmpty()){
value.push(temp.pop());
}
}
}

// Removes the element from in front of queue.


public void pop() {
value.pop();
}

// Get the front element.


public int peek() {
return value.peek();
}

// Return whether the queue is empty.

285 | 531

279 of
239 of 246
288
116 Implement Queue using Stacks

public boolean empty() {


return value.isEmpty();
}
}

286 | 531 Program Creek

280 of
240 of 246
288
117 Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

117.1 Java Solution 1

We can create a new list in reversed order and then compare each node. The time and
space are O(n).
public boolean isPalindrome(ListNode head) {
if(head == null)
return true;

ListNode p = head;
ListNode prev = new ListNode(head.val);

while(p.next != null){
ListNode temp = new ListNode(p.next.val);
temp.next = prev;
prev = temp;
p = p.next;
}

ListNode p1 = head;
ListNode p2 = prev;

while(p1!=null){
if(p1.val != p2.val)
return false;

p1 = p1.next;
p2 = p2.next;
}

return true;
}

117.2 Java Solution 2

We can use a fast and slow pointer to get the center of the list, then reverse the second
list and compare two sublists. The time is O(n) and space is O(1).

287 | 531

281 of
241 of 246
288
117 Palindrome Linked List

public boolean isPalindrome(ListNode head) {

if(head == null || head.next==null)


return true;

//find list center


ListNode fast = head;
ListNode slow = head;

while(fast.next!=null && fast.next.next!=null){


fast = fast.next.next;
slow = slow.next;
}

ListNode secondHead = slow.next;


slow.next = null;

//reverse second part of the list


ListNode p1 = secondHead;
ListNode p2 = p1.next;

while(p1!=null && p2!=null){


ListNode temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}

secondHead.next = null;

//compare two sublists now


ListNode p = (p2==null?p1:p2);
ListNode q = head;
while(p!=null){
if(p.val != q.val)
return false;

p = p.next;
q = q.next;

return true;
}

288 | 531 Program Creek

282 of
242 of 246
288
118 Implement a Queue using an Array
in Java

There following Java code shows how to implement a queue without using any extra
data structures in Java. We can implement a queue by using an array.

import java.lang.reflect.Array;
import java.util.Arrays;

public class Queue<E> {

E[] arr;
int head = -1;
int tail = -1;
int size;

public Queue(Class<E> c, int size) {


E[] newInstance = (E[]) Array.newInstance(c, size);
this.arr = newInstance;
this.size = 0;
}

boolean push(E e) {
if (size == arr.length)
return false;

head = (head + 1) % arr.length;


arr[head] = e;
size++;

if(tail == -1){
tail = head;
}

289 | 531

283 of
243 of 246
288
118 Implement a Queue using an Array in Java

return true;
}

boolean pop() {
if (size == 0) {
return false;
}

E result = arr[tail];
arr[tail] = null;
size--;
tail = (tail+1)%arr.length;

if (size == 0) {
head = -1;
tail = -1;
}

return true;
}

E peek(){
if(size==0)
return null;

return arr[tail];
}

public int size() {


return this.size;
}

public String toString() {


return Arrays.toString(this.arr);
}

public static void main(String[] args) {


Queue<Integer> q = new Queue<Integer>(Integer.class, 5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
q.pop();
q.push(6);
System.out.println(q);
}
}

290 | 531 Program Creek

284 of
244 of 246
288
119 Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only
access to that node.
Supposed the linked list is 1 ->2 ->3 ->4 and you are given the third node with value
3, the linked list should become 1 ->2 ->4 after calling your function.

119.1 Java Solution

public void deleteNode(ListNode node) {


node.val = node.next.val;
node.next = node.next.next;
}

Is this problem too easy? Or I’m doing it wrong.

291 | 531

285 of
245 of 246
288
120 Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all
integers in the sliding window.

120.1 Java Solution

This problem is solved by using a queue.


public class MovingAverage {

LinkedList<Integer> queue;
int size;

/** Initialize your data structure here. */


public MovingAverage(int size) {
this.queue = new LinkedList<Integer>();
this.size = size;
}

public double next(int val) {


queue.offer(val);
if(queue.size()>this.size){
queue.poll();
}
int sum=0;
for(int i: queue){
sum=sum+i;
}

return (double)sum/queue.size();
}
}

293 | 531

287 of
246 of 246
288
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

1 What is SDLC?

SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.

2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead

3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User

4 What are Popular SDLC models?


Waterfall model: Waterfall model works well for smaller projects where requirements are very
well understood. The waterfall is a widely accepted SDLC model. In this approach, the whole
process of the software development is divided into various phases. In this SDLC model, the
outcome of one phase acts as the input for the next phase.
Incremental Model: The incremental model is not a separate model. It is essentially a series of
waterfall cycles. The requirements are divided into groups at the start of the project. For each
group, the SDLC model is followed to develop software. The SDLC process is repeated, with
each release adding more functionality until all requirements are met. In this method, every
cycle act as the maintenance phase for the previous software release. Modification to the
incremental model allows development cycles to overlap. After that subsequent cycle may
begin before the previous cycle is complete.
V-Model: In this type of SDLC model testing and the development, the phase is planned in
parallel. So, there are verification phases on the side and the validation phase on the other side.
V-Model joins by Coding phase.
Agile Model: Agile methodology is a practice which promotes continue interaction of
development and testing during the SDLC process of any project. In the Agile method, the
entire project is divided into small incremental builds. All of these builds are provided in
iterations, and each iteration lasts from one to three weeks. In ‘Agile Model’ after every sprint
there is a demoable feature to the customer. Hence customer can see the features whether
they are satisfying their need or not. Each release is thoroughly tested to ensure software
quality is maintained. It is used for time critical applications.

Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.

5 What is Software Testing?


According to ANSI/IEEE 1059 standard – A process of analyzing a software item to detect
the differences between existing and required conditions (i.e., defects) and to evaluate the
features of the software item.

6 What are the principles of software testing?


6.1 Testing shows presence of defects
Software Testing reduces the probability of undiscovered defects remaining in the
software but even if no defects are found, it is not a proof of correctness.
6.2 Exhaustive testing is impossible
If you were testing this Operating system, you would realize that defects are likely to be
found in multi-tasking activity and need to be tested thoroughly which brings us to our
next principal Defect Clustering.
6.3 Early testing
Early Testing - Testing should start as early as possible in the Software Development Life
Cycle. So that any defects in the requirements or design phase are captured in early
stages.
6.4 Defect clustering
Defect Clustering which states that a small number of modules contain most of the
defects detected. If the same tests are repeated over and over again, eventually the
same test cases will no longer find new bugs.
6.5 Pesticide Paradox
Repetitive use of the same pesticide mixes to eradicate insects during farming will over
time led to the insect’s developing resistance to the pesticide Thereby ineffective of
pesticides on insects. The same applies to software testing. If the same set of repetitive
tests are conducted, the method will be useless for discovering new defects. To
overcome this, the test cases need to be regularly reviewed & revised, adding new &
different test cases to help find more defects.
6.6 Testing is context depending
Testing is context dependent which basically means that the way you test an ecommerce site
will be different from the way you test a commercial off the shelf
application. All the developed software’s are not identical. You might use a different
approach, methodologies, techniques, and types of testing depending upon the
application type.
6.7 Absence of error - Fallacy
It is possible that software which is 99% bug-free is still unusable. This can be the case if
the system is tested thoroughly for the wrong requirement. The absence of Error is a
Fallacy i.e. Finding and fixing defects does not help if the system build is unusable and
does not fulfill the user's needs & requirements.

7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.

Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.

9 What are the Quality assurance and Quality Control standards?


Quality assurance system standards, including ISO 9001, are defined as frameworks that
provide regulations to organizations to ensure that their processes, inputs, products, and
services are capable of meeting every customer requirement.
• Ensuring maximum satisfaction of clients by meeting their quality requirements
• Safety of products and services during usage
• Complying with international regulations and local legislative rules
• Being environmentally responsible
• Confidentiality of stakeholders including customers, employees, partners, and investors
• Assuring a safer workplace for employees
• Optimum allocation of resources and minimization of waste

10 What is Verification & Validation in software testing?


• Validation: Are we building the right system?
• Verification: Are we building the system, right?

In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.

11 What is Test Plan Document?


Test plan document is a document which contains the plan for all the testing activities to be
done to deliver a quality product. Test Plan document is derived from the Product
Description, SRS, or Use Case documents for all future activities of the project. It is usually
prepared by the Test Lead or Test Manager.
1. Test plan identifier
2. References
3. Introduction
4. Test items (functions)
5. Software risk issues
6. Features to be tested
7. Features not to be tested
8. Approach
9. Items pass/fail criteria
10. Suspension criteria and resolution requirements
11. Test deliverables
12. Remaining test tasks
13. Environmental needs
14. Staff and training needs
15. Responsibility
16. Schedule
17. Plan risks and contingencies
18. Approvals
19. Glossaries

12 What is Test Strategy?


Test Strategy is a high-level document (static document) and usually developed by project
manager. It is a document which captures the approach on how we go about testing the
product and achieve the goals. It is normally derived from the Business Requirement
Specification (BRS). Documents like Test strategy doc is project-based document it can
change according to project domain and requirements.

13 What is Test Suite?


Test Suite is a collection of test cases. The test cases which are intended to test an
application.

14 What is Test Scenario?


Test Scenario gives the idea of what we have to test. Test Scenario is like a high-level test
case.

15 What is Test Case?


Test cases are the set of positive and negative executable steps of a test scenario which has
a set of pre-conditions, test data, expected result, post-conditions and actual results.

16 What is Test Bed?


An environment configured for testing. Test bed consists of hardware, software, network
configuration, an application under test, other related software.

17 What is Test Environment?


Test Environment is the combination of hardware and software on which Test Team
performs testing. Example:
• Application Type: Web Application
• OS: Windows
• Web Server: IIS
• Web Page Design: Dot Net
• Client-Side Validation: JavaScript
• Server-Side Scripting: ASP Dot Net
• Database: MS SQL Server
• Browser: IE/Firefox/Chrome

18 What is Test Data?


Test data is the data that is used by the testers to run the test cases. Whilst running the test
cases, testers need to enter some input data. To do so, testers prepare test data. It can be
prepared manually and also by using tools.

19 What is Test Harness?


Test Harness in Software Testing is a collection of stubs, drivers and other supporting tools
required to automate test execution. Test harness executes tests by using a test library and
generates test reports. Test harness contains all the information needed to compile and run
a test like test cases, target deployment port (TDP), source file under test, stubs, etc.
20 What is Test Closure?
Test Closure is the note prepared before test team formally completes the testing process.
This note contains the total no. of test cases, total no. of test cases executed, total no. of
defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected
etc.,

21 What is Risk Factor and its Types?


In software testing Risks are the possible problems that might endanger the objectives of
the project stakeholders. It is the possibility of a negative or undesirable outcome. A risk is
something that has not happened yet and it may never happen; it is a potential problem.
The types of Risk in a Test Project can be broadly categorized as
1. Strategy Risk: This includes Budget, Communication and Management risks
2. Project Definition Risks: This includes Project target, Scope, and requirements risks.
3. Human Resources Risk: This includes Skill, Team members and organization risks.

22 What are the tasks of Test Closure activities in Software Testing?


Test Closure activities fall into four major groups.
Test Completion Check: To ensure all tests should be either run or deliberately skipped
and all known defects should be either fixed, deferred for a future release or accepted as a
permanent restriction.
Test Artifacts handover: Tests and test environments should be handed over to those
responsible for maintenance testing. Known defects accepted or deferred should be
documented and communicated to those who will use and support the use of the system.
Lessons learned: Analyzing lessons learned to determine changes needed for future
releases and projects. In retrospective meetings, plans are established to ensure that good
practices can be repeated and poor practices are not repeated.
Result: Archiving results, logs, reports, and other documents and work products in the
CMS (configuration management system).

23 List out Test Deliverables?


1. Test Strategy
2. Test Plan
3. Effort Estimation Report
4. Test Scenarios
5. Test Cases/Scripts
6. Test Data
7. Requirement Traceability Matrix (RTM)
8. Defect Report/Bug Report
9. Test Execution Report
10. Graphs and Metrics
11. Test summary report
12. Test incident report
13. Test closure report
14. Release Note
15. Installation/configuration guide
16. User guide
17. Test status report
18. Weekly status report (Project manager to client)

24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status

25 Types of Traceability Test Matrix


In Software Engineering, traceability matrix can be divided into three major components as
mentioned below:
• Forward traceability: This matrix is used to check whether the project progresses in the
• forward desired direction and for the right product. It maps requirements to test cases.
• Backward or reverse traceability: It is used to ensure whether the current product
• remains on the right track. It maps test cases to requirements.
• Bi-directional traceability (Forward + Backward): This traceability matrix ensures that all
• requirements are covered by test cases. It analyzes the impact of a change in
• requirements affected by the Defect in a work product and vice versa.

26 How to create Requirement Traceability Matrix?


On the basis of the Business Requirement Document (BRD) and Technical Requirement
Document (TRD), testers start writing test cases.
Step 1: Our sample Test Case is
"Verify Login, when correct ID and Password is entered, it should log in successfully"
Step 2: Identify the Technical Requirement that this test case is verifying. For our test case, the
technical requirement is T94 is being verified.
Step 3: Note this Technical Requirement (T94) in the Test Case.
Step 4: Identify the Business Requirement for which this TR (Technical Requirement-T94) is
defined
Step 5: Note the BR (Business Requirement) in Test Case
Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your Test Suite. RTM
in testing is Ready!

27 Advantage of Requirement Traceability Matrix


• It confirms 100% test coverage
• It highlights any requirements missing or document inconsistencies
• It shows the overall defects or execution status with a focus on business requirements
• It helps in analyzing or estimating the impact on the QA team's work with respect to
• revisiting or re-working on the test cases.

28 What is Test Coverage?


Test Coverage states which requirements of the customers are to be verified when the
testing phase starts. Test Coverage is a term that determines whether the test cases are
written and executed to ensure to test the software application completely, in such a
way that minimal or NIL defects are reported.

29 How to achieve Test Coverage?


The maximum Test Coverage can be achieved by establishing good ‘Requirement
Traceability’.
• Mapping all internal defects to the test cases designed
• Mapping all the Customer Reported Defects (CRD) to individual test cases for the
• future regression test suite.

30 Methods of Software Testing


There are 3 methods of software testing.
1) White box 2) Black box 3) Grey Box

31 What is White Box Testing?


White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on
applications internal code structure. In white-box testing, an internal perspective of the
system, as well as programming skills, are used to design test cases. This testing usually was
done at the unit level.
32 What is Black Box Testing?
Black Box Testing is a software testing method in which testers evaluate the functionality of the
software under test without looking at the internal code structure. This can be applied to every
level of software testing such as Unit, Integration, System and Acceptance Testing.

33 What is Grey Box Testing?


Grey box is the combination of both White Box and Black Box Testing. The tester who works on
this type of testing needs to have access to design documents. This helps to create better test
cases in this process.

34 What is Alpha Testing?


Alpha testing is done by the in-house developers (who developed the software) and testers.
Sometimes alpha testing is done by the client or outsourcing team with the presence of
developers or testers.
It has two phases:
• In the first phase of alpha testing, the software is tested by in-house developers. They
• use debugger software. The goal is to catch bugs quickly.
• In the second phase of alpha testing, the software is handed over to the software QA
• staff, for additional testing in an environment that is similar to the intended use.

35 What is Beta Testing?


Beta testing is done by a limited number of end users before delivery. Usually, it is done in
the client places.

36 What is Gamma Testing?


Gamma testing is done when the software is ready for release with specified requirements.
It is done at the client place. It is done directly by skipping all the in-house testing activities.

37 What is Functional Testing?


In simple words, what the system actually does is functional testing. To verify that each
function of the software application behaves as specified in the requirement document.
Testing all the functionalities by providing appropriate input to verify whether the actual
output is matching the expected output or not. It falls within the scope of black box testing
and the testers need not concern about the source code of the application.

37.1 What is Unit/Module Testing?


Unit Testing is also called as Module Testing or Component Testing. It is done to check
whether the individual unit or module of the source code is working properly. It is done
by the developers in the developer’s environment.

37.2 What is Integration Testing?


Integration Testing is the process of testing the interface between the two software
units. Integration testing is done by three ways. Big Bang Approach, Top-Down
Approach, Bottom-Up Approach.

37.3 What is System Testing?


Testing the fully integrated application to evaluate the system’s compliance with its
specified requirements is called System Testing End to End testing. Verifying the
completed system to ensure that the application works as intended or not.
System testing is carried out by specialist testers or independent testers.
System testing should investigate both functional and non-functional requirements of
the testing.

37.4 What is Smoke Testing?


Smoke Testing is done to make sure if the build we received from the development
team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It
helps not to waste the testing time to simply testing the whole application when the key
features don’t work or the key bugs have not been fixed yet.

37.5 What is Sanity Testing?


Sanity Testing is done during the release phase to check for the main functionalities of
the application without going deeper. It is also called as a subset of Regression testing. It
is done at the “release level”. We perform sanity testing when we don’t have enough
time for regression testing.

37.6 What is Regression Testing?


Repeated testing of an already tested program, after modification, to discover any
defects introduced or uncovered as a result of the changes in the software being tested
or in another related or unrelated software components.
Usually, we do regression testing in the following cases:
1. New functionalities are added to the application
2. Change Requirement (In organizations, we call it as CR)
3. Defect Fixing
4. Performance Issue Fix
5. Environment change (E.g., Updating the DB from MySQL to Oracle)
37.7 What is Retesting Testing?
Retesting is done to make sure that the tests cases which failed in last execution are
passed after the defects are fixed. Retesting is carried out based on the defect fixes. In
Retesting, the cases which are failed earlier can be included to check if the functionality
failure in an earlier build.

37.8 What is Exploratory Testing?


Usually, this process will be carried out by domain experts. They perform testing just by
exploring the functionalities of the application without having the knowledge of the
requirements.

38 What is Monkey Testing?


Perform abnormal action on the application deliberately in order to verify the stability of
the application.

39 What is Big Bang Approach?


Combining all the modules once and verifying the functionality after completion of
individual module testing.

40 What is Top-Down Approach?


Testing takes place from top to bottom. High-level modules are tested first and then lowlevel
modules and finally integrating the low-level modules to a high level to ensure the
system is working as intended. Stubs are used as a temporary module if a module is not
ready for integration testing.

41 What is Bottom-Up Approach?


It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up.
Lowest level modules are tested first and then high-level modules and finally integrating the
high-level modules to a low level to ensure the system is working as intended. Drivers are
used as a temporary module for integration testing.

42 What is User Acceptance Testing / UAT? imp


It is also known as pre-production testing. This is done by the end users along with the
testers to validate the functionality of the application. After successful acceptance
testing. Formal testing conducted to determine whether an application is developed as per
the requirement. It allows the customer to accept or reject the application. Types of
acceptance testing is Alpha, Beta & Gamma.
43 What is Positive and Negative Testing?
Positive Testing: It is to determine what system supposed to do. It helps to check
whether the application is justifying the requirements or not.
Negative Testing: It is to determine what system not supposed to do. It helps to find
the defects from the software.

44. What is Non-Functional Testing?


In simple words, how well the system performs is non-functionality testing. Nonfunctional
testing refers to various aspects of the software such as performance, load,
stress, scalability, security, compatibility etc., Main focus is to improve the user
experience on how fast the system responds to a request.

44.1. What is Performance Testing?


This type of testing determines or validates the speed, scalability, and/or stability
characteristics of the system or application under test. Performance is concerned with
achieving response times, throughput, and resource-utilization levels that meet the
performance objectives for the project or product.

44.2. What is Load Testing?


It is to verify that the system/application can handle the expected number of
transactions and to verify the system/application behavior under both normal and peak
load conditions.

44.3. What is Volume Testing?


It is to verify that the system/application can handle a large amount of data.

44.4. What is Stress Testing?


It is to verify the behavior of the system once the load increases more than its design
expectations.

44.5. What is Scalability Testing?


Scalability testing is a type of non-functional testing. It is to determine how the
application under test scales with increasing workload.

44.6. What is Concurrency Testing?


Concurrency testing means accessing the application at the same time by multiple users
to ensure the stability of the system. This is mainly used to identify deadlock issues.
44.7. What is GUI Testing?
Graphical User Interface Testing is to test the interface between the application and the
end user.

44.8. What is Recovery Testing?


Recovery testing is performed in order to determine how quickly the system can recover
after the system crash or hardware failure. It comes under the type of non-functional
testing.

44.9. What is Installation Testing?


It is to check whether the application is successfully installed and it is working as
expected after installation.

44.10. What is Formal Testing?


It is a process where the testers test the application by having pre-planned
procedures and proper documentation.

44.11. What is Risk Based Testing?


Identify the modules or functionalities which are most likely cause failures and then
testing those functionalities.

44.12. What is Compatibility Testing?


It is to deploy and check whether the application is working as expected in a different
combination of environmental components.

44.13. What is Usability Testing?


To verify whether the application is user-friendly or not and was comfortably used by an
end user or not. The main focus in this testing is to check whether the end user can
understand and operate the application easily or not. An application should be selfexploratory
and must not require training to operate it.

44.14. What is Security Testing?


Security testing is a process to determine whether the system protects data and
maintains functionality as intended.

45 What is Soak Testing?


Running a system at high load for a prolonged period of time to identify the
performance problems is called Soak or Endurance Testing.
46 What is Fuzz Testing?
Fuzz testing is used to identify coding errors and security loopholes in an application. By
inputting massive amount of random data to the system in an attempt to make it crash
to identify if anything breaks in the application.

47 What is Adhoc Testing?


Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In
Adhoc testing, testers randomly test the application without following any documents
and test design techniques. This testing is primarily performed if the knowledge of
testers in the application under test is very high. Testers randomly test the application
without any test cases or any business requirement document.

48 What is Interface Testing?


Interface testing is performed to evaluate whether two intended modules pass data and
communicate correctly to one another.

49 What is Reliability Testing?


Perform testing on the application continuously for long period of time in order to verify
the stability of the application.

50 What is Bucket Testing? imp


Bucket or Split testing is a method to compare two versions of an application against
each other to determine which one performs better.

51 What is Defect Cascading in Software Testing?


Defect cascading in Software testing means triggering of other defects in an application.
When a defect is not identified or goes unnoticed while testing, it invokes other defects.
It leads to multiple defects in the later stages and results in an increase in a number of
defects in the application.
For example, if there is a defect in an accounting system related to negative taxation
then the negative taxation defect affects the ledger which in turn affects other reports
such as Balance Sheet, Profit & Loss etc.,

52 What is Walk Through?


A walkthrough is an informal meeting conducts to learn, gain understanding, and find
defects. The author leads the meeting and clarifies the queries raised by the peers in the
meeting.
53 What is Inspection?
Inspection is a formal meeting lead by a trained moderator, certainly not by the author.
The document under inspection is prepared and checked thoroughly by the reviewers
before the meeting. In the inspection meeting, the defects found are logged and shared
with the author for appropriate actions. Post inspection, a formal follow-up process is
used to ensure a timely and corrective action.

54 Who are all involved in an inspection meeting?


Author, Moderator, Reviewer(s), Scribe/Recorder and Manager.

55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.

56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.

57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.

58 What is Bug Severity?


Bug/Defect severity can be defined as the impact of the bug on customer’s business. It
can be Critical, Major or Minor. In simple words, how much effect will be there on the
system because of a particular defect.

59 What is Bug Priority?


Defect priority can be defined as how soon the defect should be fixed. It gives the order
in which a defect should be resolved. Developers decide which defect they should take
up next based on the priority. It can be High, Medium or Low. Most of the times the
priority status is set based on the customer requirement.

60 Tell some examples of Bug Severity and Bug Priority?


High Priority & High Severity: Submit button is not working on a login page and
customers are unable to login to the application
Low Priority & High Severity: key feature failed but there’s no impact on customer
business, e.g., calculation fault in yearly report which end user won’t use on daily basis.
High Priority & Low Severity: Spelling mistake of a company name on the homepage
Low Priority & Low Severity: FAQ page takes a long time to load

61 What is a Critical Bug?


A critical bug is a show stopper which means a large piece of functionality or major
system component is completely broken and there is no workaround to move further.
For example, Due to a bug in one module, we cannot test the other modules because
that blocker bug has blocked other modules. Bugs which affect the customers’ business
are considered as critical.
Example:
1. “Sign In” button is not working on Gmail App and Gmail users are blocked to login to
their accounts.
2. An error message pops up when a customer clicks on transfer money button in a
Banking website.

62 What are entry criteria?


Entry criteria is a set of conditions that permits a task to perform, or in absence of any of
these conditions, the task cannot be performed.
• The requirement document should be available.
• Complete understanding of the application flow is required.
• The Test Plan Document should be ready.

63 What is exit criteria?


Exit criteria is a set of expectations; this should be met before concluding the STLC
phase.
• Test Cases should be written and reviewed.
• Test Data should be identified and ready.
• Test automation script should be ready if applicable.

64 What is the Test Management Reviews & Audit?


Management Review is also known as Software Quality Assurance or (SQA). It focuses
more on the software process rather than the software work products. Quality
Assurance is a set of activities designed to ensure that the project manager follows the
standard process which is already pre-defined. In other words, Quality Assurance makes
sure, the Test Manager is doing the right things in the right way.
An audit is the examination of the work products and related information to assesses
whether the standard process was followed or not.
65 What is the difference between functional and non-functional testing?
Functional Testing Non Functional Testing

Performed before non-functional testing Performed after functional testing

Based on customer requirements Based on customers’ expectations

Describes what the product does Describes how the product works

66 On what basis the acceptance plan is prepared?


Basically, the acceptance document is prepared using the following inputs.
• Requirement document: It specifies what exactly is needed in the project from the
customers perspective.
• Input from the customer: This can be discussions, informal talks, emails, etc.
• Project plan: The project plan prepared by the project manager also serves as good
input to finalize your acceptance test.

67 What is a Test Report? What does it include?


Test report is basically a document that includes a total summary of testing objectives,
activities, and results. It is very much required to reflect testing results and gives an opportunity
to estimate testing results quickly. It helps us to decide whether the product is ready for release
or not. It also helps us determine the current status of the project and the quality of the
product. A test report must include the following details:
• Test Objective
• Project Information
• Defect
• Test Summary
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

1 What is SDLC?

SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.

2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead

3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User

4 What are Popular SDLC models?


Waterfall model: Waterfall model works well for smaller projects where requirements are very
well understood. The waterfall is a widely accepted SDLC model. In this approach, the whole
process of the software development is divided into various phases. In this SDLC model, the
outcome of one phase acts as the input for the next phase.
Incremental Model: The incremental model is not a separate model. It is essentially a series of
waterfall cycles. The requirements are divided into groups at the start of the project. For each
group, the SDLC model is followed to develop software. The SDLC process is repeated, with
each release adding more functionality until all requirements are met. In this method, every
cycle act as the maintenance phase for the previous software release. Modification to the
incremental model allows development cycles to overlap. After that subsequent cycle may
begin before the previous cycle is complete.
V-Model: In this type of SDLC model testing and the development, the phase is planned in
parallel. So, there are verification phases on the side and the validation phase on the other side.
V-Model joins by Coding phase.
Agile Model: Agile methodology is a practice which promotes continue interaction of
development and testing during the SDLC process of any project. In the Agile method, the
entire project is divided into small incremental builds. All of these builds are provided in
iterations, and each iteration lasts from one to three weeks. In ‘Agile Model’ after every sprint
there is a demoable feature to the customer. Hence customer can see the features whether
they are satisfying their need or not. Each release is thoroughly tested to ensure software
quality is maintained. It is used for time critical applications.

Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.

5 What is Software Testing?


According to ANSI/IEEE 1059 standard – A process of analyzing a software item to detect
the differences between existing and required conditions (i.e., defects) and to evaluate the
features of the software item.

6 What are the principles of software testing?


6.1 Testing shows presence of defects
Software Testing reduces the probability of undiscovered defects remaining in the
software but even if no defects are found, it is not a proof of correctness.
6.2 Exhaustive testing is impossible
If you were testing this Operating system, you would realize that defects are likely to be
found in multi-tasking activity and need to be tested thoroughly which brings us to our
next principal Defect Clustering.
6.3 Early testing
Early Testing - Testing should start as early as possible in the Software Development Life
Cycle. So that any defects in the requirements or design phase are captured in early
stages.
6.4 Defect clustering
Defect Clustering which states that a small number of modules contain most of the
defects detected. If the same tests are repeated over and over again, eventually the
same test cases will no longer find new bugs.
6.5 Pesticide Paradox
Repetitive use of the same pesticide mixes to eradicate insects during farming will over
time led to the insect’s developing resistance to the pesticide Thereby ineffective of
pesticides on insects. The same applies to software testing. If the same set of repetitive
tests are conducted, the method will be useless for discovering new defects. To
overcome this, the test cases need to be regularly reviewed & revised, adding new &
different test cases to help find more defects.
6.6 Testing is context depending
Testing is context dependent which basically means that the way you test an ecommerce site
will be different from the way you test a commercial off the shelf
application. All the developed software’s are not identical. You might use a different
approach, methodologies, techniques, and types of testing depending upon the
application type.
6.7 Absence of error - Fallacy
It is possible that software which is 99% bug-free is still unusable. This can be the case if
the system is tested thoroughly for the wrong requirement. The absence of Error is a
Fallacy i.e. Finding and fixing defects does not help if the system build is unusable and
does not fulfill the user's needs & requirements.

7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.

Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.

9 What are the Quality assurance and Quality Control standards?


Quality assurance system standards, including ISO 9001, are defined as frameworks that
provide regulations to organizations to ensure that their processes, inputs, products, and
services are capable of meeting every customer requirement.
• Ensuring maximum satisfaction of clients by meeting their quality requirements
• Safety of products and services during usage
• Complying with international regulations and local legislative rules
• Being environmentally responsible
• Confidentiality of stakeholders including customers, employees, partners, and investors
• Assuring a safer workplace for employees
• Optimum allocation of resources and minimization of waste

10 What is Verification & Validation in software testing?


• Validation: Are we building the right system?
• Verification: Are we building the system, right?

In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.

11 What is Test Plan Document?


Test plan document is a document which contains the plan for all the testing activities to be
done to deliver a quality product. Test Plan document is derived from the Product
Description, SRS, or Use Case documents for all future activities of the project. It is usually
prepared by the Test Lead or Test Manager.
1. Test plan identifier
2. References
3. Introduction
4. Test items (functions)
5. Software risk issues
6. Features to be tested
7. Features not to be tested
8. Approach
9. Items pass/fail criteria
10. Suspension criteria and resolution requirements
11. Test deliverables
12. Remaining test tasks
13. Environmental needs
14. Staff and training needs
15. Responsibility
16. Schedule
17. Plan risks and contingencies
18. Approvals
19. Glossaries

12 What is Test Strategy?


Test Strategy is a high-level document (static document) and usually developed by project
manager. It is a document which captures the approach on how we go about testing the
product and achieve the goals. It is normally derived from the Business Requirement
Specification (BRS). Documents like Test strategy doc is project-based document it can
change according to project domain and requirements.

13 What is Test Suite?


Test Suite is a collection of test cases. The test cases which are intended to test an
application.

14 What is Test Scenario?


Test Scenario gives the idea of what we have to test. Test Scenario is like a high-level test
case.

15 What is Test Case?


Test cases are the set of positive and negative executable steps of a test scenario which has
a set of pre-conditions, test data, expected result, post-conditions and actual results.

16 What is Test Bed?


An environment configured for testing. Test bed consists of hardware, software, network
configuration, an application under test, other related software.

17 What is Test Environment?


Test Environment is the combination of hardware and software on which Test Team
performs testing. Example:
• Application Type: Web Application
• OS: Windows
• Web Server: IIS
• Web Page Design: Dot Net
• Client-Side Validation: JavaScript
• Server-Side Scripting: ASP Dot Net
• Database: MS SQL Server
• Browser: IE/Firefox/Chrome

18 What is Test Data?


Test data is the data that is used by the testers to run the test cases. Whilst running the test
cases, testers need to enter some input data. To do so, testers prepare test data. It can be
prepared manually and also by using tools.

19 What is Test Harness?


Test Harness in Software Testing is a collection of stubs, drivers and other supporting tools
required to automate test execution. Test harness executes tests by using a test library and
generates test reports. Test harness contains all the information needed to compile and run
a test like test cases, target deployment port (TDP), source file under test, stubs, etc.
20 What is Test Closure?
Test Closure is the note prepared before test team formally completes the testing process.
This note contains the total no. of test cases, total no. of test cases executed, total no. of
defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected
etc.,

21 What is Risk Factor and its Types?


In software testing Risks are the possible problems that might endanger the objectives of
the project stakeholders. It is the possibility of a negative or undesirable outcome. A risk is
something that has not happened yet and it may never happen; it is a potential problem.
The types of Risk in a Test Project can be broadly categorized as
1. Strategy Risk: This includes Budget, Communication and Management risks
2. Project Definition Risks: This includes Project target, Scope, and requirements risks.
3. Human Resources Risk: This includes Skill, Team members and organization risks.

22 What are the tasks of Test Closure activities in Software Testing?


Test Closure activities fall into four major groups.
Test Completion Check: To ensure all tests should be either run or deliberately skipped
and all known defects should be either fixed, deferred for a future release or accepted as a
permanent restriction.
Test Artifacts handover: Tests and test environments should be handed over to those
responsible for maintenance testing. Known defects accepted or deferred should be
documented and communicated to those who will use and support the use of the system.
Lessons learned: Analyzing lessons learned to determine changes needed for future
releases and projects. In retrospective meetings, plans are established to ensure that good
practices can be repeated and poor practices are not repeated.
Result: Archiving results, logs, reports, and other documents and work products in the
CMS (configuration management system).

23 List out Test Deliverables?


1. Test Strategy
2. Test Plan
3. Effort Estimation Report
4. Test Scenarios
5. Test Cases/Scripts
6. Test Data
7. Requirement Traceability Matrix (RTM)
8. Defect Report/Bug Report
9. Test Execution Report
10. Graphs and Metrics
11. Test summary report
12. Test incident report
13. Test closure report
14. Release Note
15. Installation/configuration guide
16. User guide
17. Test status report
18. Weekly status report (Project manager to client)

24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status

25 Types of Traceability Test Matrix


In Software Engineering, traceability matrix can be divided into three major components as
mentioned below:
• Forward traceability: This matrix is used to check whether the project progresses in the
• forward desired direction and for the right product. It maps requirements to test cases.
• Backward or reverse traceability: It is used to ensure whether the current product
• remains on the right track. It maps test cases to requirements.
• Bi-directional traceability (Forward + Backward): This traceability matrix ensures that all
• requirements are covered by test cases. It analyzes the impact of a change in
• requirements affected by the Defect in a work product and vice versa.

26 How to create Requirement Traceability Matrix?


On the basis of the Business Requirement Document (BRD) and Technical Requirement
Document (TRD), testers start writing test cases.
Step 1: Our sample Test Case is
"Verify Login, when correct ID and Password is entered, it should log in successfully"
Step 2: Identify the Technical Requirement that this test case is verifying. For our test case, the
technical requirement is T94 is being verified.
Step 3: Note this Technical Requirement (T94) in the Test Case.
Step 4: Identify the Business Requirement for which this TR (Technical Requirement-T94) is
defined
Step 5: Note the BR (Business Requirement) in Test Case
Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your Test Suite. RTM
in testing is Ready!

27 Advantage of Requirement Traceability Matrix


• It confirms 100% test coverage
• It highlights any requirements missing or document inconsistencies
• It shows the overall defects or execution status with a focus on business requirements
• It helps in analyzing or estimating the impact on the QA team's work with respect to
• revisiting or re-working on the test cases.

28 What is Test Coverage?


Test Coverage states which requirements of the customers are to be verified when the
testing phase starts. Test Coverage is a term that determines whether the test cases are
written and executed to ensure to test the software application completely, in such a
way that minimal or NIL defects are reported.

29 How to achieve Test Coverage?


The maximum Test Coverage can be achieved by establishing good ‘Requirement
Traceability’.
• Mapping all internal defects to the test cases designed
• Mapping all the Customer Reported Defects (CRD) to individual test cases for the
• future regression test suite.

30 Methods of Software Testing


There are 3 methods of software testing.
1) White box 2) Black box 3) Grey Box

31 What is White Box Testing?


White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on
applications internal code structure. In white-box testing, an internal perspective of the
system, as well as programming skills, are used to design test cases. This testing usually was
done at the unit level.
32 What is Black Box Testing?
Black Box Testing is a software testing method in which testers evaluate the functionality of the
software under test without looking at the internal code structure. This can be applied to every
level of software testing such as Unit, Integration, System and Acceptance Testing.

33 What is Grey Box Testing?


Grey box is the combination of both White Box and Black Box Testing. The tester who works on
this type of testing needs to have access to design documents. This helps to create better test
cases in this process.

34 What is Alpha Testing?


Alpha testing is done by the in-house developers (who developed the software) and testers.
Sometimes alpha testing is done by the client or outsourcing team with the presence of
developers or testers.
It has two phases:
• In the first phase of alpha testing, the software is tested by in-house developers. They
• use debugger software. The goal is to catch bugs quickly.
• In the second phase of alpha testing, the software is handed over to the software QA
• staff, for additional testing in an environment that is similar to the intended use.

35 What is Beta Testing?


Beta testing is done by a limited number of end users before delivery. Usually, it is done in
the client places.

36 What is Gamma Testing?


Gamma testing is done when the software is ready for release with specified requirements.
It is done at the client place. It is done directly by skipping all the in-house testing activities.

37 What is Functional Testing?


In simple words, what the system actually does is functional testing. To verify that each
function of the software application behaves as specified in the requirement document.
Testing all the functionalities by providing appropriate input to verify whether the actual
output is matching the expected output or not. It falls within the scope of black box testing
and the testers need not concern about the source code of the application.

37.1 What is Unit/Module Testing?


Unit Testing is also called as Module Testing or Component Testing. It is done to check
whether the individual unit or module of the source code is working properly. It is done
by the developers in the developer’s environment.

37.2 What is Integration Testing?


Integration Testing is the process of testing the interface between the two software
units. Integration testing is done by three ways. Big Bang Approach, Top-Down
Approach, Bottom-Up Approach.

37.3 What is System Testing?


Testing the fully integrated application to evaluate the system’s compliance with its
specified requirements is called System Testing End to End testing. Verifying the
completed system to ensure that the application works as intended or not.
System testing is carried out by specialist testers or independent testers.
System testing should investigate both functional and non-functional requirements of
the testing.

37.4 What is Smoke Testing?


Smoke Testing is done to make sure if the build we received from the development
team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It
helps not to waste the testing time to simply testing the whole application when the key
features don’t work or the key bugs have not been fixed yet.

37.5 What is Sanity Testing?


Sanity Testing is done during the release phase to check for the main functionalities of
the application without going deeper. It is also called as a subset of Regression testing. It
is done at the “release level”. We perform sanity testing when we don’t have enough
time for regression testing.

37.6 What is Regression Testing?


Repeated testing of an already tested program, after modification, to discover any
defects introduced or uncovered as a result of the changes in the software being tested
or in another related or unrelated software components.
Usually, we do regression testing in the following cases:
1. New functionalities are added to the application
2. Change Requirement (In organizations, we call it as CR)
3. Defect Fixing
4. Performance Issue Fix
5. Environment change (E.g., Updating the DB from MySQL to Oracle)
37.7 What is Retesting Testing?
Retesting is done to make sure that the tests cases which failed in last execution are
passed after the defects are fixed. Retesting is carried out based on the defect fixes. In
Retesting, the cases which are failed earlier can be included to check if the functionality
failure in an earlier build.

37.8 What is Exploratory Testing?


Usually, this process will be carried out by domain experts. They perform testing just by
exploring the functionalities of the application without having the knowledge of the
requirements.

38 What is Monkey Testing?


Perform abnormal action on the application deliberately in order to verify the stability of
the application.

39 What is Big Bang Approach?


Combining all the modules once and verifying the functionality after completion of
individual module testing.

40 What is Top-Down Approach?


Testing takes place from top to bottom. High-level modules are tested first and then lowlevel
modules and finally integrating the low-level modules to a high level to ensure the
system is working as intended. Stubs are used as a temporary module if a module is not
ready for integration testing.

41 What is Bottom-Up Approach?


It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up.
Lowest level modules are tested first and then high-level modules and finally integrating the
high-level modules to a low level to ensure the system is working as intended. Drivers are
used as a temporary module for integration testing.

42 What is User Acceptance Testing / UAT? imp


It is also known as pre-production testing. This is done by the end users along with the
testers to validate the functionality of the application. After successful acceptance
testing. Formal testing conducted to determine whether an application is developed as per
the requirement. It allows the customer to accept or reject the application. Types of
acceptance testing is Alpha, Beta & Gamma.
43 What is Positive and Negative Testing?
Positive Testing: It is to determine what system supposed to do. It helps to check
whether the application is justifying the requirements or not.
Negative Testing: It is to determine what system not supposed to do. It helps to find
the defects from the software.

44. What is Non-Functional Testing?


In simple words, how well the system performs is non-functionality testing. Nonfunctional
testing refers to various aspects of the software such as performance, load,
stress, scalability, security, compatibility etc., Main focus is to improve the user
experience on how fast the system responds to a request.

44.1. What is Performance Testing?


This type of testing determines or validates the speed, scalability, and/or stability
characteristics of the system or application under test. Performance is concerned with
achieving response times, throughput, and resource-utilization levels that meet the
performance objectives for the project or product.

44.2. What is Load Testing?


It is to verify that the system/application can handle the expected number of
transactions and to verify the system/application behavior under both normal and peak
load conditions.

44.3. What is Volume Testing?


It is to verify that the system/application can handle a large amount of data.

44.4. What is Stress Testing?


It is to verify the behavior of the system once the load increases more than its design
expectations.

44.5. What is Scalability Testing?


Scalability testing is a type of non-functional testing. It is to determine how the
application under test scales with increasing workload.

44.6. What is Concurrency Testing?


Concurrency testing means accessing the application at the same time by multiple users
to ensure the stability of the system. This is mainly used to identify deadlock issues.
44.7. What is GUI Testing?
Graphical User Interface Testing is to test the interface between the application and the
end user.

44.8. What is Recovery Testing?


Recovery testing is performed in order to determine how quickly the system can recover
after the system crash or hardware failure. It comes under the type of non-functional
testing.

44.9. What is Installation Testing?


It is to check whether the application is successfully installed and it is working as
expected after installation.

44.10. What is Formal Testing?


It is a process where the testers test the application by having pre-planned
procedures and proper documentation.

44.11. What is Risk Based Testing?


Identify the modules or functionalities which are most likely cause failures and then
testing those functionalities.

44.12. What is Compatibility Testing?


It is to deploy and check whether the application is working as expected in a different
combination of environmental components.

44.13. What is Usability Testing?


To verify whether the application is user-friendly or not and was comfortably used by an
end user or not. The main focus in this testing is to check whether the end user can
understand and operate the application easily or not. An application should be selfexploratory
and must not require training to operate it.

44.14. What is Security Testing?


Security testing is a process to determine whether the system protects data and
maintains functionality as intended.

45 What is Soak Testing?


Running a system at high load for a prolonged period of time to identify the
performance problems is called Soak or Endurance Testing.
46 What is Fuzz Testing?
Fuzz testing is used to identify coding errors and security loopholes in an application. By
inputting massive amount of random data to the system in an attempt to make it crash
to identify if anything breaks in the application.

47 What is Adhoc Testing?


Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In
Adhoc testing, testers randomly test the application without following any documents
and test design techniques. This testing is primarily performed if the knowledge of
testers in the application under test is very high. Testers randomly test the application
without any test cases or any business requirement document.

48 What is Interface Testing?


Interface testing is performed to evaluate whether two intended modules pass data and
communicate correctly to one another.

49 What is Reliability Testing?


Perform testing on the application continuously for long period of time in order to verify
the stability of the application.

50 What is Bucket Testing? imp


Bucket or Split testing is a method to compare two versions of an application against
each other to determine which one performs better.

51 What is Defect Cascading in Software Testing?


Defect cascading in Software testing means triggering of other defects in an application.
When a defect is not identified or goes unnoticed while testing, it invokes other defects.
It leads to multiple defects in the later stages and results in an increase in a number of
defects in the application.
For example, if there is a defect in an accounting system related to negative taxation
then the negative taxation defect affects the ledger which in turn affects other reports
such as Balance Sheet, Profit & Loss etc.,

52 What is Walk Through?


A walkthrough is an informal meeting conducts to learn, gain understanding, and find
defects. The author leads the meeting and clarifies the queries raised by the peers in the
meeting.
53 What is Inspection?
Inspection is a formal meeting lead by a trained moderator, certainly not by the author.
The document under inspection is prepared and checked thoroughly by the reviewers
before the meeting. In the inspection meeting, the defects found are logged and shared
with the author for appropriate actions. Post inspection, a formal follow-up process is
used to ensure a timely and corrective action.

54 Who are all involved in an inspection meeting?


Author, Moderator, Reviewer(s), Scribe/Recorder and Manager.

55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.

56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.

57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.

58 What is Bug Severity?


Bug/Defect severity can be defined as the impact of the bug on customer’s business. It
can be Critical, Major or Minor. In simple words, how much effect will be there on the
system because of a particular defect.

59 What is Bug Priority?


Defect priority can be defined as how soon the defect should be fixed. It gives the order
in which a defect should be resolved. Developers decide which defect they should take
up next based on the priority. It can be High, Medium or Low. Most of the times the
priority status is set based on the customer requirement.

60 Tell some examples of Bug Severity and Bug Priority?


High Priority & High Severity: Submit button is not working on a login page and
customers are unable to login to the application
Low Priority & High Severity: key feature failed but there’s no impact on customer
business, e.g., calculation fault in yearly report which end user won’t use on daily basis.
High Priority & Low Severity: Spelling mistake of a company name on the homepage
Low Priority & Low Severity: FAQ page takes a long time to load

61 What is a Critical Bug?


A critical bug is a show stopper which means a large piece of functionality or major
system component is completely broken and there is no workaround to move further.
For example, Due to a bug in one module, we cannot test the other modules because
that blocker bug has blocked other modules. Bugs which affect the customers’ business
are considered as critical.
Example:
1. “Sign In” button is not working on Gmail App and Gmail users are blocked to login to
their accounts.
2. An error message pops up when a customer clicks on transfer money button in a
Banking website.

62 What are entry criteria?


Entry criteria is a set of conditions that permits a task to perform, or in absence of any of
these conditions, the task cannot be performed.
• The requirement document should be available.
• Complete understanding of the application flow is required.
• The Test Plan Document should be ready.

63 What is exit criteria?


Exit criteria is a set of expectations; this should be met before concluding the STLC
phase.
• Test Cases should be written and reviewed.
• Test Data should be identified and ready.
• Test automation script should be ready if applicable.

64 What is the Test Management Reviews & Audit?


Management Review is also known as Software Quality Assurance or (SQA). It focuses
more on the software process rather than the software work products. Quality
Assurance is a set of activities designed to ensure that the project manager follows the
standard process which is already pre-defined. In other words, Quality Assurance makes
sure, the Test Manager is doing the right things in the right way.
An audit is the examination of the work products and related information to assesses
whether the standard process was followed or not.
65 What is the difference between functional and non-functional testing?
Functional Testing Non Functional Testing

Performed before non-functional testing Performed after functional testing

Based on customer requirements Based on customers’ expectations

Describes what the product does Describes how the product works

66 On what basis the acceptance plan is prepared?


Basically, the acceptance document is prepared using the following inputs.
• Requirement document: It specifies what exactly is needed in the project from the
customers perspective.
• Input from the customer: This can be discussions, informal talks, emails, etc.
• Project plan: The project plan prepared by the project manager also serves as good
input to finalize your acceptance test.

67 What is a Test Report? What does it include?


Test report is basically a document that includes a total summary of testing objectives,
activities, and results. It is very much required to reflect testing results and gives an opportunity
to estimate testing results quickly. It helps us to decide whether the product is ready for release
or not. It also helps us determine the current status of the project and the quality of the
product. A test report must include the following details:
• Test Objective
• Project Information
• Defect
• Test Summary
By Fang Ying, Sham

Structured Query language (SQL)


SQL Commands

DCL (deals with access


TCL (deals with the DQL (retrieve data
DDL (define database DML (manipulate data rights and data control
transactions happening from the DB using SQL
schema in DBMS) present in the DB) on the data present in
in the DB) queries)
the db)

CREATE INSERT GRANT COMMIT SELECT

DROP UPDATE REVOKE ROLLBACK

ALTER DELETE
DDL : Data Definition Language DML: Data Manipulation Language
TRUNCATE DCL : Data Control Language TCL : Transaction Control Language
DQL : Data Query Language

1. Create database create database sample2


2. Use the database use sample2
3. Create table create table customer
(
customerid int identity(1,1) primary key,
customernumber int not null unique check (customernumber>0),
lastname varchar(30) not null,
firstname varchar(30) not null,
areacode int default 71000,
address varchar(50),
country varchar(50) default 'Malaysia'
)
4. Insert values into table insert into customer values
(100,'Fang Ying','Sham','418999','sdadasfdfd',default),
(200,'Mei Mei','Tan',default,'adssdsadsd','Thailand'),
(300,'Albert','John',default,'dfdsfsdf',default)

5. Display record from table -- display all records


select * from customer

-- display particular columns


select customerid, customernumber, lastname, firstname
from customer
6. Add new column to table alter table customer
add phonenumber varchar(20)
7. Add values to newly added update customer set phonenumber='1234545346' where
column/ Update table customerid=1
update customer set phonenumber='45554654' where
customerid=2
8. Delete a column alter table customer
drop column phonenumber
9. Delete record from table delete
--if not put ‘where’, will from customer
delete all record where country='Thailand'
10. Delete table drop table customer
11. Change data type alter table customer
alter column phonenumber varchar(10)

1
By Fang Ying, Sham

1. Create database create database SaleOrder


2. Use the database use SaleOrder
3. Create tables create table dbo.customer (
CustomerID int NOT null primary key,
CustomerFirstName varchar(50) NOT null,
CustomerLastName varchar(50) NOT null,
CustomerAddress varchar(50) NOT null,
CustomerSuburb varchar(50) null,
CustomerCity varchar(50) NOT null,
CustomerPostCode char(4) null,
CustomerPhoneNumber char(12) null,
);

create table dbo.inventory (


InventoryID tinyint NOT null primary key,
InventoryName varchar(50) NOT null,
InventoryDescription varchar(255) null,
);

create table dbo.employee (


EmployeeID tinyint NOT null primary key,
EmployeeFirstName varchar(50) NOT null,
EmployeeLastName varchar(50) NOT null,
EmployeeExtension char(4) null,
);

create table dbo.sale (


SaleID tinyint not null primary key,
CustomerID int not null references customer(CustomerID),
InventoryID tinyint not null references Inventory(InventoryID),
EmployeeID tinyint not null references Employee(EmployeeID),
SaleDate date not null,
SaleQuantity int not null,
SaleUnitPrice smallmoney not null
);

4. Check what table inside select * from information_schema.tables


5. View specific row --top: show only the first two
select top 2 * from customer

--top 40 percent: also means show the first two


select top 40 percent * from customer

6. View specific column --sort result (by default is ascending)


select customerfirstname, customerlastname from customer
order by customerlastname desc

select customerfirstname, customerlastname from customer


order by 4, 2, 3 desc -- Order By Based on column no. without typing column
name

--distinct: only show unique value


select distinct customerlastname from customer
order by customerlastname

2
By Fang Ying, Sham

7. Save table to another table --into file_name: save result in another table (BASE TABLE)
select distinct customerlastname into temp
from customer
order by customerlastname

select * from temp --see the table (data type will remain)

8. Like (search something) -- (underscore sign) _ is only specific for one character only
-- (percent sign) % represents zero, one, or multiple characters
select * from customer
where customerlastname like '_r%'

9. In (search something) -- search multiple items


select * from customer
where customerlastname in ('Brown', ‘Michael’, ’Jim’)

10. > (search something) select * from customer


where customerlastname > 'Brown' or customerlastname>'Cross'
11. <> (Not Equal) select * from customer
where customerlastname <> 'Brown'

12. IS NULL -- check null values


select * from customer
where customerlastname IS NULL

13. IS NOT NULL select * from customer


where customerlastname IS NOT NULL

14. between select * from sale


where saleunitprice between 5 and 10 --not include 5 & 10

15. count -- returns the number of rows in a table


-- AS means aliasing, temporary giving name to a column/ table
select count(*) as [Number of Records] from customer
where customerfirstname like 'B%'

16. sum select sale.employeeid ,EmployeeFirstName, EmployeeLastName , count(*) as


[Number of order] ,
sum(salequantity) as [Total Quantity]
from sale,employee
where sale.employeeid = employee.employeeid
group by sale.employeeid ,EmployeeFirstName, EmployeeLastName

17. count month select month(saledate) as [Month], count ( * ) as [Number of sale],


sum(salequantity*saleunitprice) as [Total Amount]
from sale
group by month(saledate)

18. max SELECT MAX(Salary)


FROM EmployeeSalary
19. min SELECT MIN(Salary)
FROM EmployeeSalary
20. average SELECT AVG(Salary)
FROM EmployeeSalary

3
By Fang Ying, Sham

21. having SELECT JobTitle, COUNT(JobTitle)


FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID
GROUP BY JobTitle
HAVING COUNT(JobTitle) > 1

SELECT JobTitle, AVG(Salary)


FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID
GROUP BY JobTitle
HAVING AVG(Salary) > 45000
ORDER BY AVG(Salary)
22. Change data type -- CAST(expression AS datatype(length))
temporary for use SELECT CAST('2017-08-25 00:00:00.000' AS date)

-- CONVERT(data_type(length), expression, style)


SELECT CONVERT(date,'2017-08-25 00:00:00.000')

23. CASE Statement SELECT FirstName, LastName, Age,


CASE
WHEN Age > 30 THEN 'Old'
WHEN Age BETWEEN 27 AND 30 THEN 'Young'
ELSE 'Baby'
END
FROM EmployeeDemographics ED
WHERE Age IS NOT NULL
ORDER BY Age

--
SELECT FirstName, LastName, JobTitle, Salary,
CASE
WHEN JobTitle = 'Salesman' THEN Salary + (Salary *.10)
WHEN JobTitle = 'Accountant' THEN Salary + (Salary *.05)
WHEN JobTitle = 'HR' THEN Salary + (Salary *.000001)
ELSE Salary + (Salary *.03)
END AS SalaryAfterRaise
FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID

24. Partition By SELECT FirstName, LastName, Gender, Salary,


--returns a single value for each COUNT(Gender) OVER (PARTITION BY Gender) AS TotalGender
row FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID

4
By Fang Ying, Sham

25. String Functions -- Remove space


Select EmployeeID, TRIM(EmployeeID) AS IDTRIM
FROM EmployeeErrors

Select EmployeeID, RTRIM(EmployeeID) as IDRTRIM


FROM EmployeeErrors

Select EmployeeID, LTRIM(EmployeeID) as IDLTRIM


FROM EmployeeErrors

-- Replace
Select LastName, REPLACE(LastName, '- Fired', '') as
LastNameFixed
FROM EmployeeErrors

-- Substring
Select Substring(err.FirstName,1,3),
Substring(dem.FirstName,1,3), Substring(err.LastName,1,3),
Substring(dem.LastName,1,3)
FROM EmployeeErrors err
JOIN EmployeeDemographics dem
on Substring(err.FirstName,1,3) =
Substring(dem.FirstName,1,3)
and Substring(err.LastName,1,3) =
Substring(dem.LastName,1,3)

-- UPPER and LOWER CASE


Select firstname, LOWER(firstname)
from EmployeeErrors

Select Firstname, UPPER(FirstName)


from EmployeeErrors"

26. Stored Procedure CREATE PROCEDURE Temp_Employee


@JobTitle nvarchar(100)
AS
DROP TABLE IF EXISTS #temp_employee
Create table #temp_employee (
JobTitle varchar(100),
EmployeesPerJob int ,
AvgAge int,
AvgSalary int
)

Insert into #temp_employee


SELECT JobTitle, Count(JobTitle), Avg(Age), AVG(salary)
FROM EmployeeDemographics emp
JOIN EmployeeSalary sal
ON emp.EmployeeID = sal.EmployeeID
where JobTitle = @JobTitle --- make sure to change this in
this script from original above
group by JobTitle

Select *
From #temp_employee
GO;

5
By Fang Ying, Sham

--- only need to run this on next time


EXEC Temp_Employee @JobTitle = 'Salesman'

27. Subquery -- Subquery in Select


SELECT EmployeeID, Salary, (SELECT AVG(Salary) FROM
EmployeeSalary) AS AllAvgSalary
FROM EmployeeSalary

-- with Partition By
SELECT EmployeeID, Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary

-- Subquery in From
SELECT a.EmployeeID, AllAvgSalary
FROM (SELECT EmployeeID, Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary) a
ORDER BY a.EmployeeID

-- Subquery in Where
SELECT EmployeeID, JobTitle, Salary
FROM EmployeeSalary
WHERE EmployeeID in (SELECT EmployeeID FROM
EmployeeDemographics
WHERE Age > 30)

SELECT EmployeeID, JobTitle, Salary


FROM EmployeeSalary
WHERE Salary in (SELECT Max(Salary) FROM EmployeeSalary)

6
By Fang Ying, Sham

SQL JOINS

Inner Join Self Join Outer Join Cross Join

Left Outer Join Right Outer Join Full Outer Join

1. getting data from multiple select * from inventory,sale


tables where sale.inventoryid=inventory.inventoryid
(explicit join - without using
join command) select
inventoryname,saledate,saleunitprice,salequantity,salequantity*saleunitprice
as [Total amount]
from sale,inventory
where sale.inventoryid=inventory.inventoryid
group by sale.inventoryid,inventoryname,saledate,salequantity,saleunitprice
order by inventoryname

2. getting data from multiple --inner join


tables select * from inventory
(implicit join - using join inner join sale
command) on sale.inventoryid=inventory.inventoryid

select
inventoryname,saledate,saleunitprice,salequantity,saleunitprice*salequantity
as [Total Amount]
from inventory inner join sale
on sale.inventoryid=inventory.inventoryid
order by inventoryname

inventory sales

--full outer join (shows everything)


select sale.inventoryid,inventoryname
from inventory
full outer join sale on
sale.inventoryid=inventory.inventoryid
where sale.inventoryid is NULL

inventory sales

7
By Fang Ying, Sham

--left join (might have NULL value, since some inventory might not have sales)
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid

inventory sales

--left join
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid
where sale.inventoryid is NULL

inventory sales

-- without join: use subquery


select inventoryid,inventoryname from inventory
where inventoryid not in (select inventoryid from sale)

--right join
select sale.inventoryid,inventoryname
from inventory right join sale on
sale.inventoryid=inventory.inventoryid

inventory sales

3. Self Join --inner join


--commonly used in processing Staff Table
hierarchy employeeID employeefirstname employeelastname managerID
1001 Tan Mei Ling NULL
1002 Kelvin Koh 1001
1003 Amin Wong 1002

select E.employeeID, E.employeefirstname+' '+E.employeelastname as [Full


Name], E.managerID, , M.employeefirstname+' '+M.employeelastname as
[Manager Name]
from staff E
inner join staff M
on E.managerID = M.employeeID

8
By Fang Ying, Sham

Output:
employeeID Full Name managerID managerName
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh

--left outer join (list all the employees)


select E.employeeID, E.employeefirstname+' '+E.employeelastname as [F
Name], E.managerID, , M.employeefirstname+' '+M.employeelastname as
[Manager Name]
from staff E
left outer join staff M
on E.managerID = M.employeeID

Output:
employeeID Full Name managerID managerName
1001 Tan Mei Ling
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh

4. Cross Join select * from inventory1


--generate all combination of cross join inventory2
records (all possibility)
(Cartesian Product)

9
By Fang Ying, Sham

SQL UNIONS
1. Union
--allow you to combine two tables select cust_lname,cust_fname from customer
together (but the no. of columns & union
each column’s data types for 2 tables select cust_lname,cust_fname from customer_2
must be match)
--don't need common key, only need
common attributes
--merge, not showing duplicate record

2. Union all select cust_lname,cust_fname from customer


--merge, but show you everything, even union all
the duplicate record select cust_lname,cust_fname from customer_2

customer customer_2

3. Intersect select cust_lname,cust_fname from customer


--keep only the rows in common to intersect
both query select cust_lname,cust_fname from customer_2
--not showing duplicate record

customer customer_2

select c.cust_lname,c.cust_fname from customer c,customer_2 c2


where c.cust_lname=c2.cust_lname and c.cust_fname=c2.cust_fname

4. Except select cust_lname,cust_fname from customer


--generate only the records that are except
unique to select cust_lname,cust_fname from customer_2
the CUSTOMER table

customer customer_2

--use subquery
select cust_lname,cust_fname from customer
where(cust_lname) not in
(select cust_lname from customer_2) and
(cust_fname) not in
(select cust_fname from customer_2)

10
By Fang Ying, Sham

Table & View


1. view table create view CustomerView as
(view will be updated when select customerfirstname+' '+customerlastname as [Customer Name] ,
update base) customerphonenumber,
--view is a result set of SQL inventoryname,saledate,salequantity,saleunitprice,salequantity*saleunitprice
statements, exists only for a as [Total Amount]
single query from customer inner join sale on customer.customerid=sale.customerid inner
join inventory
on sale.inventoryid=inventory.inventoryid

customer

inventory sales

2. Temp table DROP TABLE IF EXISTS #temp_Employee


(temp will NOT be updated
Create table #temp_Employee (
when update base) JobTitle varchar(100),
--a single hashtag (#) sign EmployeesPerJob int,
must be added in front of AvgAge int,
their names AvgSalary int
--used to store data )
temporarily, physically Insert INTO #temp_Employee
created in the Tempdb SELECT JobTitle, Count(JobTitle), Avg(Age), AVG(salary)
database FROM EmployeeDemographics emp
--can perform CRUD, join, and JOIN EmployeeSalary sal
ON emp.EmployeeID = sal.EmployeeID
some other operations like
group by JobTitle
the persistent database tables
SELECT * FROM #temp_Employee

3. CTE (Common Table WITH CTE_Employee AS


Expression) (
SELECT FirstName, LastName, Gender, Salary,
--create temporary result set COUNT(Gender) OVER (PARTITION BY Gender) AS TotalGender
which is used to manipulate FROM EmployeeDemographics ED
the complex sub-queries data JOIN EmployeeSalary ES
--created in memory rather ON ED.EmployeeID = ES.EmployeeID
than Tempdb database, so WHERE Salary > '45000'
)
cannot create any index on
CTE. SELECT FirstName, LastName, Gender, TotalGender
FROM CTE_Employee
WHERE TotalGender = (SELECT MIN(TotalGender) FROM CTE_Employee)

4. Duplicate Table select customerfirstname+' '+customerlastname as [Customer Name] ,


customerphonenumber,
inventoryname,saledate,salequantity,saleunitprice,salequantity*saleunitprice
as [Total Amount] into customerRec
from customer inner join sale on customer.customerid=sale.customerid inner
join inventory
on sale.inventoryid=inventory.inventoryid
order by customerfirstname +' '+ customerlastname,inventoryname

11
By Fang Ying, Sham

SQL RANKS
1. ROW_NUMBER() --get a unique sequential number for each row
--get different ranks for the row having similar values

SELECT *,
ROW_NUMBER() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary

2. RANK() --specify rank for each row in the result set


--use PARTITION BY to performs calculation on each group
--each subset get rank as per Salary in descending order

USING PARTITION BY
SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank

NOT USING PARTITION BY


-- get SAME ranks for the row having similar values
SELECT *,
RANK() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank

12
By Fang Ying, Sham

3. DENSE_RANK()
-- if have duplicate values, SQL assigns different ranks to those rows.
-- will get the same rank for duplicate or similar values

SELECT *,
DENSE_RANK() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank

RANK() DENSE_RANK()

SELECT *, SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER DENSE_RANK() OVER(PARTITION BY JobTitle
BY Salary DESC) SalaryRank ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank ORDER BY JobTitle, SalaryRank

-- skip a rank if have similar values -- maintains the rank and does not give any gap
for the values

13
By Fang Ying, Sham

4. NTILE() -- can specify required how many group of result, and it will rank accordingly

SELECT *,
NTILE(3) OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank;

Group 1

Group 2

Group 3

USING PARTITION BY
SELECT *,
NTILE(3) OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank;

Group 1
Group 2
Group 3

14
By Fang Ying, Sham

1. Write the query to show the select


invoice number, the customer invoice_num,c.cust_num,c.cust_lname,c.cust_fname,inv_date,inv_amount
number, the customer from customer c, invoice
name, the invoice date, and the where c.cust_num=invoice.cust_num and cust_balance>=1000
invoice amount for all
customers with a customer select invoice_num,c.cust_num,cust_lname+' '+cust_fname as
balance [Name],inv_date,inv_amount
of $1,000 or more. from customer c join invoice i
on c.cust_num=i.cust_num
where cust_balance>=1000

2. ISNULL(expression, value) --ParcelID is same, but UniqueID is different; can assume that if the ParcelID is
--expression: to test whether is same, the Property Address will be same
NULL, value: to return if Select a.ParcelID, a.PropertyAddress, b.ParcelID,
expression is NULL b.PropertyAddress,
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null

-- Update record
Update a
SET PropertyAddress =
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null

3. Split by delimiter SELECT PropertyAddress,


SUBSTRING(PropertyAddress, 1, CHARINDEX(',',
❖ SUBSTRING(string, start, PropertyAddress) -1 ) as Address
length) , SUBSTRING(PropertyAddress, CHARINDEX(',',
PropertyAddress) + 1 , LEN(PropertyAddress)) as City
❖ CHARINDEX(substring, From NashvilleHousing
string, start)

❖ LEN(string)

ALTER TABLE NashvilleHousing


Add PropertySplitAddress Nvarchar(255);

ALTER TABLE NashvilleHousing


Add PropertySplitCity Nvarchar(255);

15
By Fang Ying, Sham

Update NashvilleHousing
SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1,
CHARINDEX(',', PropertyAddress) -1 )

Update NashvilleHousing
SET PropertySplitCity = SUBSTRING(PropertyAddress,
CHARINDEX(',', PropertyAddress) + 1 , LEN(PropertyAddress))

Select OwnerAddress,
PARSENAME(REPLACE(OwnerAddress, ',', '.') , 3)
❖ PARSENAME('object_name' ,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 2)
, object_piece) ,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 1)
From NashvilleHousing
--numbering works from
right to left

❖ REPLACE(string, old_string,
new_string)

ALTER TABLE NashvilleHousing


Add OwnerSplitAddress Nvarchar(255);
ALTER TABLE NashvilleHousing
Add OwnerSplitCity Nvarchar(255);
ALTER TABLE NashvilleHousing
Add OwnerSplitState Nvarchar(255);

Update NashvilleHousing
SET OwnerSplitAddress = PARSENAME(REPLACE(OwnerAddress,
',', '.') , 3)

Update NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 2)

Update NashvilleHousing
SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 1)

5. Remove duplicate records WITH RowNumCTE AS(


Select *,
ROW_NUMBER() OVER (
PARTITION BY ParcelID,
PropertyAddress,
SalePrice,
SaleDate,
LegalReference
ORDER BY UniqueID) as row_num
From NashvilleHousing
order by ParcelID
)
--DELETE
Select * From RowNumCTE
Where row_num > 1
Order by PropertyAddress

16
Low
-

Level
= Design
- Kapil Yadav

- OOPs concepts

- Design Principles

- Design Patterns
Kapil Yadav
-

INDEX

1 .
Classes and
objects .

2- Access Modifiers in Ctt .


public

Private (friend class and
friend fume] .

→ Protected

3 . Constructor


Default

Parameterized

copy
4. static
keyword
5 .
This keyword
6 .

New keyword
7. Const
keyword
8- Final
keyword
9.
Explicit keyword

10 .
Inheritance
Inheritance
single

Multiple

Inheritance
→ Inheritance
Multilevel

Hierarchical Inheritance

Hybrid Inheritance .

11 "

Polymorphism

Compile Time
Polymorphism
Function
overloading


operator overloading
Kapil Yadav

polymorphism
→ Run time

virtual Functions

12 .
Encapsulation

13 .
Data Abstraction

1. OOPS DESIGN PRINCIPLES



DRY
• KISS
• YAGNI

2. COHESION & COUPLING


3. CQS
4. SOLID

OOPS DESIGN PATTERN


Pattern :
17
Factory Method
Design
-

2. SINGLETON DESIGN PATTERN : -

Builder
3.
Design Pattern
Design Pattern
4. Observer
5 Abstract
.

Factory Design

linkedin.com/in/kapilyadav22
Kapil Yadav
-

class : -

Blueprint

→ state /Property /field/data member
design / type
*m⑦ behaviour / function / data function .

Humans hand

→§ }→
Ex - 2
state /properties
Leg
2

↓ 2
eyes
behaviour → walk eat
, speak , .

Architect class ,
gives Blueprint
→ is the
using
Blueprint ,
we make the house is object .

memory / space
takes class does 't
Object

.
,

Object is an implementation / seal


entity/
instance of class .

→ class is a
logical component .


Object takes
memory from heap .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Access Modifiers in C++ : -

One of the main features of 00ps is data


Hiding .

Data
Hiding
: -
Data
hiding refers to
restricting access

to data members of a class .


This is to prevent other

functions and classes from tampering with the class


data .

→ The access modifiers of C++ allows us to determine

which class members are accessible to other classes and

functions ,
and which are not .

→ There are 3
types of access modifiers available in
C++ .

I. Public

2 .
Private
3. Protected

By default ,
The access modifier of the members will be Private .

1. Public :
keyword used create
The
public is to
public
-

members (data and functions] .

accessible
The
public members from part of the

are
any
program .

The public members be accessed from the


anywhere in

can
program
using
direct
memory
access
operator C.) with the
object
of that class .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Private Access Modifier : -

The
private keyword is used to create
private members

(data and
functions ] .


The private members can
only be accessed from
within the class .


However , friend classes and friend functions can access

private members .

data members of class


we the
private

can access a

indirectly using the public member functions of the

class .

linkedin.com/in/kapilyadav22
Kapil Yadav

Friend class ? -
A friend class can access private and
class it
protected members of other in which is

defined as friend .
It is sometimes used to allow
a
particular class to access
private members of
other class .

linkedin.com/in/kapilyadav22
Kapil Yadav

Friend Function : -

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Protected Access Modifier : -

→ Protected Access Modifier is similar to


private access modifier ,

→ But the difference is


protected members can be access

within the class and from the desired class as well .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

CONSTRUCTOR.com/stnectoris a special method that is invoked


automatically
at the time
of object creation .

initialize data
objects

It is used to the members new
of .

return
Constructors don't have
type

any
.

Constructor have class


itself
→ the
same name as .


don't
If we
specify a constructor, C++
compiler generates
a default constructor for object .


It should be placed in public section
of
class .

→ It can be overloaded .

Constructors in C++

Default Parameterized copy


we can do constructor private .
But what will

happen ?

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

→ Do constructor returns
any
value ?
No constructor does not return value
,
any
.
Kapil Yadav

STATIC KEYWORD : -

↳ static variables : variables in a


function ,

variables in a class

class and functions


static Members of class : -

objects
in a class .

class static member is accessed class


In
using

, ,

not
object .

class Human {

static ént count ;

Human C)
{ count tt ;

y
3; 11 initialize static member of class Human

int Human : : count -0


;

int main C)
E coat <<
Human : : count -
Lendl ;

ng

Q ? Can static data member


I access without
creating an

object ?
Anis .
Yes .

linkedin.com/in/kapilyadav22
Kapil Yadav

Static function → can


change static Data Member .
.

Cannot static Data Member


change the value
of non -
.
Kapil Yadav

NOTE : -
A non
-
static member function can
modify
a static data member as
long as the data member 's

visibility allows it .

keyword method

we cannot use this in static .

Q? why main function in Java is static ?


And

linkedin.com/in/kapilyadav22
Kapil Yadav

THIS
keyword :
-


Object Pointer A pointer contains address
of
-

called Pointer
an
object is
object .

local
this
object pointer in every
→ is a

instance member
function containing address
of the caller
object .

→ this
pointer cannot be
modify .

caller
→ 9T is used to refer object in member

function .

Friend functions do not have this pointer



,

because
friends are not members of a class .

Only member
functions have a this
pointer .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

NEW KEYWORD : -

→ The new is a
memory
allocation operator ,

which is used to allocate at the


memory
runtime .

→ The
memory initialized by
the new operator is

allocated in a
heap .

returns
It the
starting address of the

memory,
variable
which
get assigned to the .

Syntax type variable new


type (parameter list) ;
-
=
-

variable
Type datatype of
• -

a .


variable -
name of the variable .

parameter - list -

is the list of values that are

initialized to a variable .

int *
pts =
new int ;

WHAT IS MALLOC ?
→ Malbec ) is function that allocates at
a
memory
the runtime .


Syntax
-

type variable name -


-

Ctypetamalloclsizeofctype));
variable
type it és the
datatype of

: the .


variable -
name : it defines the name of the variable

that points to the


memory .

(type *) for that


typecasting
• : It is used so we can

get the
pointer of specified type
a that

to the
points memory
.

linkedin.com/in/kapilyadav22
Kapil Yadav

NOTE :
-
The mallocc ) function returns the void pointer ,

$0
typecasting is
required to
assign a different
type to the
pointer The sizeof
.
operator is

required in the mallee function as the Malbec)

function returns the raw


memory ,
so the
sizeofc)
operator will tell the Malloch) function ,
how

much
memory
is
required for the allocation .

Allocation New
→ Memory using

delete p ;

linkedin.com/in/kapilyadav22
Kapil Yadav

Allocation mallee
Memory using
: -


If the sufficient memory is not available ,
mallee function returns the NULL
pointer .


de allocate
using free
Allocated can be
memory
function .

linkedin.com/in/kapilyadav22
Kapil Yadav

Difference between New and Maller


EW MALLOC

1. New
operator construct 1 . Mallee is a
function ,
it does

(it calls the constructor


an
object not call the .

constructor to
initialize
an
object .

2. delete operator to
destroy
2.
free function to deallocate
the
the
object .

memory .

3. new is an
operator 3 . It is predefined function
a

in stdlib.tn header file .

4. new can be overloaded . 4 . Mallock ) cannot be overloaded .

5-
If sufficient memory is not 5 . Malloch ) will seteem a NULL

available , new will throw pointers .

an
exception

6. we need to
specify 6
. We need to
specify number
allocated
number of objects .

of bytes
to be .

7. allocated be reallocated
memory by new 7 . It can
using
cannot be resized .
ocallocc)
function .

8. Execution time of new is 8 . E T


-
is more than new .

less than mallee

linkedin.com/in/kapilyadav22
Kapil Yadav

FINAL
keyword : _

→ a-+11 allows built-in


facility to
prevent
overriding of virtual function using final specifier .

overriding final
'
error -

functions
'

'

derive
error : -
cannot
from
'
final
' '
base '
Base in
' '
derived Derived
type

linkedin.com/in/kapilyadav22
Kapil Yadav

CONST KEYWORD ! -

→ Const
keywords used to define the constant
value that cannot
change during program
execution .

Use of const
keyword with different parameters : -


Use const variable

const with
Use
pointers

Use const with variables


pointer


Use const with function arguments

Use const with class member functions

class data members



Use const with .

Use class
objects

const with .

1. Consent variable
const int a- 20 ;

a -_ at 105
OUTPUT : -
error .

2. Const pointer
cannot address of const
we
change the the

pointer after its


initialization ,
which means the

pointer will
alwaysis point to the same address

once the pointer initialized as the const

pointer .

linkedin.com/in/kapilyadav22
Kapil Yadav

3. Pointer to constant variable

→ It means pointer points to the value of


a const variable that cannot
change .

Const into a;
]→ both pointer
are
to

char constant variable


constancy ;
Kapil Yadav

4. Constant function Arguments

linkedin.com/in/kapilyadav22
Kapil Yadav

5. Const
pointer pointing to a const variable : _

const
Syntax const datatypes varname ;
-
Kapil Yadav

6. Pass const
argument value to a non const
parameter of
- -

a function cause error : -

'
→ •
into ?
from
'
error : -
invalid conversion const intro to

For return Tetum


7. const
type : the
type of
-

the function is const and so it returns a

const value to
integer us .

→ There will be no issue whether

we
pass const or non
-

const
variable to the
function because
the value will be oeteerned

by the
function will be

constant
automatically .

As the
the
argument of
function is non
-
const .

linkedin.com/in/kapilyadav22
Kapil Yadav

8. For return
const
type and const
parameter : -

→ Here ,
both const and non -
const values can be

passed as the const


parameter to the
function ,

but not allowed to


we are then
change the
value
of
a
passed variable because the
parameter
is const .

Otherwise
,
we will face the error .

"

y is a const war its value can't be


changed .

linkedin.com/in/kapilyadav22
Kapil Yadav

Inheritance ? -

In C++, there are 5


types of Inheritance .

1.
Single
2. Multilevel
3. Hierarchical
4.
Multiple 3- Not in Java
5-
Hybrid
17 Base class
Single : -


☒ → derived class

output : 35 60

linkedin.com/in/kapilyadav22
Kapil Yadav

2) Multilevel 1-

Car

t
Toyota


Innova

linkedin.com/in/kapilyadav22
Kapil Yadav

37 Hierarchical ?

Employee

< ]

Intern FTE

linkedin.com/in/kapilyadav22
Kapil Yadav

Multiples speaks speaks .

MOM DAD

cH%D
classes
There Be
ambiguity the Base

can ,
when

functions have same name to soothe this : -

use
scope resolution operator .

scope
g→ oesolution
operator
Kapil Yadav

Hybrid ?
-

Vehicle

car derived from Vehicle

Car
Racing
Ferrari derived from Cart
*
Racing
Ferrari

linkedin.com/in/kapilyadav22
Kapil Yadav

ADVANTAGES : -

Reusability

code .

→ don't
Improves code
readability as we need to

rewrite the code code 100k$ Cleaner and


same
again ,
Treatable .

Inheritance classes
supports extensibility
→ as new can

classes
be
easily added to
existing
.

linkedin.com/in/kapilyadav22
Kapil Yadav

POLYMORPHISM : _

POLY MORPH
↓ ↓

Forms
Many .

→ In Ctt
, polymorphism is
mainly divided into two
types : -


Compile-time polymorphism .


Runtime Polymorphism .

Polymorphism

N
L

Compile Time Run Time

✓ ☒ ✓
Virtual
Function Operator
Functions
Overloading Overloading
1. Compile-time polymorphism : -
This
type of polymorphism
is achieved
by function overloading or
operator
overloading .

Function
Overloading
• : -

→ when there are


multiple functions with the same name

but different parameters ,


then the functions are said to be

overloaded .

Functions be overloaded
by
→ •
can .

changing the number of arguments


OR / AND
Kapil Yadav

changing the
type of arguments

.

linkedin.com/in/kapilyadav22
Kapil Yadav

Q) Can we overload main method ?


To overload main() function in C++, it is necessary to use class and declare the
main as member function. Note that main is not reserved word in programming
languages like C, C++, Java and C#. For example, we can declare a variable
whose name is main, try below example:

linkedin.com/in/kapilyadav22
Kapil Yadav

Operator Overloading : -

with
C++ has
ability
the to
provide the operators a

special meaning for a data


type, this
ability is known

as operator overloading
.

How to overload theoperator :-


To overload an
operator a operator function
,
is defined
inside a class .

class class

{
-
name

% "ᵗ" Pⁿʰ " "

return
type operator Cargs)

:
3;

Kapil Yadav
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

R-ntmeymrp.cm?-

It is achieved
by function overriding .

Function
Overriding :

-

derived class
Function
overriding has

occurs when a a

definition for one


of the member functions of the base

class . That base function is said to te overrides .

Rules →
Must do inheritance .

→ same
function name / same
parameter .

⑦7 can we override static method ?


Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav

Function ?
Virtual A virtual function is member
-

function ,
which is declare within a base class and

is overridden derived class


by a .

→ when refer to a derived class object using a


we

reference to the base class can call


pointer a or
, we

a virtual function for that object and execute


the desired class 's version of the function .

Run-time
They mainly use to achieve
→ are

polymorphism The resolving


. of function call is done at
runtime .

Functions declared virtual


with
keyword
→ are a

in the base class .

Points to remember ? -

1. virtual functions cannot be static .

2. Virtual function can be a friend function of


another class .

3 .

They are
always defined in the base class and

class (
may / maynot
overridden in a derived . we

override in the derived class , optional ) .

4. A class have virtual destructor, but it


may
cannot have a virtual constructor .

linkedin.com/in/kapilyadav22
Kapil Yadav

OUTPUT -
This is call to
parent class area

linkedin.com/in/kapilyadav22
Kapil Yadav

OUTPUT : 25
Square area :
-
.

linkedin.com/in/kapilyadav22
Kapil Yadav
Use of Virtual Function ?

It allows us to create a list
of base class pointers
and call methods derived class without
of any
even

knowing the kind of derived class


object .


working of virtual functions (concepts of VTABZE and

VPTR) .

If a class contains a virtual function then the

compiler itself does two


things .

If the class is created then


1 .

object of a

virtual pointer CVPTR) is inserted as a data


member of the class to point to VTABLE of
that class .

For each new


object created , a new virtual

pointer is inserted as a data member of that


virtual
class .

pointer is inherited
by derived
classes . .

Irrespective of not ,
2 .

object is created or

class contains as member static


array
a a

of function pointers called VTABLE .

Virtual Table -
A table created at compile time for
derived
every single class
containing the most versions

of virtual function only .

A virtual table contains


entry for

one

each virtual
function that can be
class
called
by objects of the .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

Virtual Destructor :-

Deleting a derived class

object using a
pointer of base class
type
that
has a non -
virtual destructor oesults in undefined
behaviour .

OUTPUT
constructing
: -
base

constructing derived

Destructing base

linkedin.com/in/kapilyadav22
Kapil Yadav

class used make


NOTE :
-
The base
pointer was to
class
the derived
object .

Destructor has to be made virtual otherwise


,

Derive Destructor will not call .

OUTPUT ? -

constructing base

derived
constructing
derived
Destructing
Destructing base
Kapil Yadav

⑦7 what about virtual constructor ?


Because when constructor of
It is not possible .
a

a class is executed there is no virtual table

in the
memory , means no virtual pointer defined
yet .

,
so constructor should
always be non -
virtual .

Because not
the
object created virtual

is
,

construction is impossible .


The compiler must know the type of object
before creating it .

Constructors
'
Error -

cannot be declared virtual ?


Kapil Yadav

Encapsulation : -

Encapsulation is defined as
wrapping up
of data and information under single
a unit .

Role of access
specifiers in encapsulation : -

The
process of implementing encapsulation can be scut divided
-

into two
steps : -

1. The data members should be labeled the


as
private using
private access specifiers .
Kapil Yadav

2. The member function which manipulates the data members

should be labeled as
public using the public access specifier .

→ Data encapsulation led to the important OOP


concept of
data
hiding .

tread " " "


→ we can write
only or write
only methods
data
to
implement hiding .

linkedin.com/in/kapilyadav22
Kapil Yadav

Abstraction ? Date abstraction is


process of providing
-
a

only the essential details to the outside world

details
and
hiding the internal

C++
provides great level of abstraction for

a . ex -

pow function is used to calculate the power of


a number without
knowing the
algorithm the function
follows .

Data Abstraction be achieved in two :


can
ways
-

••
Abstraction classes
using .


Abstraction in header files .

linkedin.com/in/kapilyadav22
Kapil Yadav

not allowed
directly
→ to
we are access
my,z
however them member
function
using
, we can access

of the class .

Advantages of Data Abstraction 2-

→ A does not need to write the low level


programmer
code .

→ Data abstraction avoids code duplication .

→ Increases Zeus
ability .


Implementation details class
of the are
protected from
the inadvertent user level errors .

linkedin.com/in/kapilyadav22
Kapil Yadav ①

OOPS DESIGN PRINCIPLES

Clean code ? →
easily readable
by other
developers .

Why ?
How ?

meaningful variable name
, function ,
class etc .

→ comments .

→ Modular

functions

short,

→ structured , readable , simple .

DESIGN PRINCIPLES : _

DRY Don't
repeat yourself
→ :
.

→ Kiss
keep it simple stupid
:
.


Abstraction :

Curly 's law


→ :

Boy Scout law ÷



Do better code
quality than what it was
-
.

Features of ?
Good
Design
-

l . Code Reuse : -

'

is
2.
Extensibility
:
change the
only constant
thing
_

in
programmer
's life ?

linkedin.com/in/kapilyadav22
Kapil Yadav

Naming Intension
revealing
→ -
names .


descriptive names .

-
int ✗
int getsumc ) ; a

~ ✗
b
int
getanswe.ro ; int

② lines]
Verb
Function Name dedicate
single
→ -
short to task
, ,
.


should have fewer arg cements ( Use Helper function ) .

• sort , several
, swap, pow .


Ward 's principle
-

Class Name
-

Noun

descriptive
meaningful


intent
revealing
-

linkedin.com/in/kapilyadav22 RCnMartin_
Kapil Yadav

! DRY PRINCIPLE ( Don't repeat Yourself)

law variable should


Curly 's → A mean one
thing ,
and

one
thing only .

② KISS ( Keep it
simple stupid)

if (a)
{ if (b)
{ ifcc)
{ if (d)
{ 3
else {3
3
}
3


if (a && 6 && c && d) is
simple .

Benefits ? -

easy
to read
/ understand .


less time to code .

Bugs chances less


are .

debug / modify / update


linkedin.com/in/kapilyadav22
Kapil Yadav

③ YAGNI : -
You ain't
gonna
need it .

"

Always implement things which are


actually
needed
just foresee
"
not the ones
, you .


Don't
engineering
Do over .

Benefits : -


Slave time .


concise code .

the root of all Evils



Preoptimisalin is .

Boy -
Scout Law ? -
The code
quality tends to
degrade
with each
change .
-

(tech debt .

'

leave behind better state
Always the code in a

found
"
than it
you .

linkedin.com/in/kapilyadav22
Kapil Yadav

COHESION & COUPLING : _

Cohesion related &


: -
It is the
degree of how
strongly
focused are the various responsibilities of a module .

→ Maximum cohesion .

Coupling
: -
It is the degree to which each module depend
on other modules .

HUMAN → CAR


Required low
coupling .

Command -

Query separation :(CQS)

Command the state but doesn't return



changes any
value .

Query return the stale without


changing the state
→ .

CQS → It states that method should be


every
a

command that performs an action, or a


query
that returns data to the caller, but not both .

linkedin.com/in/kapilyadav22
Kapil Yadav

Is there
exception of CQS ?
any

SOLID -
a set of principles .

S
single responsibility principle
-
.

0
Open closed
principle
-
-
.

L -
Liskov Substitution Principle
I Interface Segregation Principle
-

D-
Dependency Inversion Principle .

Single Responsibility principle :


-

class should have


A
just one reason to
change .

→ module ( module set functions class


Any of
means a
, ,

code ) should
package ,
source have a reason to
change by
only one actor .

have class have


Let's
say
we a
Employee ,
some

function calculate
salary ,
calculate hours , savec-mpdate.CI .

Calculates
alary C) CFO
-

calculatehours C) -

Technical
savec-mpdato.CI HR
-

linkedin.com/in/kapilyadav22
Kapil Yadav

used and it
If calculates
alanya by
→ is CFO
acquired
a method
getRegularHours O and make a
change in

will also calculate


getregulartloursc] ,
it
change in

Hours C) ,
which is
managed by someone else .

linkedin.com/in/kapilyadav22
Kapil Yadav

here class
→ what
happened was ,
one
exposed two or three

different methods ,
which were
corresponding to different
stakeholders of the software .

One Actor doesn't have to know about the other

actor, but still


change in the one them is
ofthe
reflected the other .

It is
voélating Single
Responsibility Principle .

Single Responsibility that


'

principle the code



means
, you
writing
code
are
, if that
requested change in one

stakeholder ,
which
fulfill one business
Requirement ,

till then it is
fine .

class have
That means ou r can more than one
public
method as
long as the
change in those
public method
is
requested by one stakeholder / group of stakeholders .

→ Create 3
different class ,
the calculation
of salary
doesn't
depend
need to know about / doesn't need on method
,
any
which is used in calculate hours .

By decomposing one class into multiple classes, we

can
actually adhere
single
sits in
oesponsiblity ,
where
the business
requirement one
particular
class , and request to
change those
logics comes from
one actor
only .

OPEN -
CLOSED PRINCIPLE
"

software entities such as classes, modules , functions etc ,
.

should be
open for extension
,
but closed for modification .

functionality should be
by

Any new implemented


classes, of
adding new attributes and methods, instead

changing the current ones or


existing ones .

Meyer originated

Bertrand the term OCP .

→ Robert c. Martin considered this as most important


principle .

Implementation Guidelines : -

→ The
simplest way to apply OCP is to
implement the

new
functionality on new derived classes .

→ Allow clients to class


access the
original with

abstract interface .

WHY OCP ?

Not
If followed

End
testing the entire
functionality

up
QA need test flow

Team to the entire .

linkedin.com/in/kapilyadav22

Costly Process for the
Organization
Breaks well
single roesponsibility

the as .

→ Maintenance overheads increase the classes


on .

1-

doesn't
It 's
design allow behaviour

to extend the unless

we
change the code .
for ex -

if we want to add new

sensormodel , we have to
change distance sensor class to

accommodate the new


functionality ,

by defining

we start what we want a distancesensor to

do below
in
general .
In code ,
Distance sensor is
generic, it

doesn't have a model


, therefore it doesn't make
any
sense

to concrete instance it
of
a .

Therefore we defined , Distance sensor as a


pure
abstract

class or in
javea we can
say interface .
→ when we create
specializations of
the interface for
,
each

Distance sensor model that need,


the
everytime
we
of
we want to add new sensor
,
we can create a new

child class ,
that implements the distance sensors interface
without
changing any existing code .

linkedin.com/in/kapilyadav22
LISKOV SUBSTITUTION PRINCIPLE ( LSP)
for
"
must substitutable their base
subtypes be

types ?
"

subtype of T objects of typet


→ s is then
a ,

"

may
be
replaced with objects of type
S

Derived substitutable
types be
completely

must

for their base


types .

→ LSP is a
particular definition of a
subtyping
relation , called C. ) behavioral
strong subtyping .

Introduced
by Barbara Leskov

.

→ Extension
of the
Open close principle .

Implementation Guidelines

No
exceptions be
by the
subtype
→ new can thrown .

→ clients should not know which specific subtype


they are
calling .

derived
New classes
just extend without
replacing

the
functionality of old classes .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

ISP Interface Segregation Principle


-

"

Dependency of one class to another should be on

smallest possible interface ?



clients should not be
forced to
implement interface
don't
they use .

fat interface

one need to be
split to
many
smaller and relevant interfaces so that clients can

know about the interfaces that are relevant

to them .


The ISP was first used and
formulated by
Robert for
c. Martin while
consulting Xerox

Case
Study
Problem ? -

had created
printer system that
→ Xerox a new

could perform a
variety of tasks such as

stapling and
faxing along with the
regular
printing task .

→ The
software for this
system was created

from the ground up .


Modifications and
Deployment to the
system
became more
complex .
SOLUTION
→ One
large Job class is
segregated to multiple
interfaces depending on the
requirement .

linkedin.com/in/kapilyadav22
public Animal
Dog
:

Animal
{ feed C);
{ feed :

Pete] ;
pet ; 3
3;

Lion :
public Animal

{ feed C) ;
pete
;✗
3

→ Pet cannot be used for Lion


,
so don't add pet function
in base class .

linkedin.com/in/kapilyadav22
Kapil Yadav

D-
Dependency inversion Principle .

"
(Interfaces)
"

Depend on Abstraction not on concrete classes .

→ level modules should not


depend low-level
High on
-

modules . Both should


depend on abstractions .


Abstractions should not depend on details . Details

should depend on
abstracl.im#- interfaces

interaction level low level


between
high and
NOTE : -
The

should be abstract
modules
thought of as an

interaction between them .

linkedin.com/in/kapilyadav22
Kapil Yadav

OOPS DESIGN PATTERN



formalised Best practices to write clean code .

Creation Factory Abstract Factory Singleton


-

, ,

structural
Bridge Adaptive, Composite
-

,
> Behavioural
Interpreter
_

, strategy ,
observer .

7)
Factory Method
Design Pattern : -

Factory Method design pattern


that define interface abstract class
stays just an or

for let subclass


creating an
object but the decide

which class to instantiate .

→ ( subclasses are
responsible to create the instances
of
the class ?
→ This pattern is also known as Virtual constructor .
Kapil Yadav

→ In above code, if user wants to add Tempo bus Metoo


, ,

info , he/she needs to add it in multiple if else ,

linkedin.com/in/kapilyadav22
Kapil Yadav

our user doesn't want to do it .

→ Now ,
we are
going to create a
factory it will
,

creation
take care
of
entire
logic without
,

it to client/ user, client will not


exposing so

bother .
Kapil Yadav

→ we created the function as static , so that we can

access the function without the


object of class .

will
logic factory if
→ Now , write and
we our in ,

client
any change required ,
will not bothered , we

only need to do
change in
factory .

Library to decide
→ be
should which
responsible obj type
create based
to on
input .

→ client should
just call
library's factory and
pass type
without
worrying
about actual
implementation of creation

of object .

Pattern :
Advantages of Factory Design -

Factory Design Pattern allows the sub-class to choose

the
type of objects to create .

loose
promotes the
couplingclasses
by eliminating the

It -

need to bind
application specific
-
into code the .

Usage of Factory Design Pattern : _


when a class doesn't know what sub-classes will
be required to create .

classes
when class wants that its sub
specify

a -

created
the
objects to be .
Kapil Yadav

Ex-2_: -

Plan
Generate bill
rate
getRate()
calculateBill()

mainC)

extends extends extends asks

Domestic Commercial Institutional GetPlanFactory


Plan Plan Plan
creates

getRate() getRate() getRate()

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

2. SINGLETON DESIGN PATTERN : -

→ New Instance Created . No .

of instances are 1

this
message
is
from user 1 .


New csnstance created .
No .

of instances are 2

this
message is from user 2 .

→ I don't want users to be able to create


my
logger object .


I want to restrict them to able to access

logger constructor .

class
1. Restrict users
from creating object of .


By making the constructor private , we are

oestoicting users
from creating object or

calling the constructor itself .


Kapil Yadav

Kapil Yadav

→ code fails In
Multithreading Case .

Suppose there are two threads


working paralleling
and
they try to create a
logger Instance ,

the first will create a


logger instance because it

is well , same second thread will also do the

same
,
so total 2 instances will be created .

linkedin.com/in/kapilyadav22
Use -
Mute , Kapil Yadav
Kapil Yadav

Our code is now safe on


multithreading but,

we don't need mutex all the time because


,

first time ,
when
logger instance = NOLL
,
and multiple
lock
threads

trying to access
loggesinstanee , we need ,
but

don't lock,
once
loggerinstance is created, we need
double
so
put check
ifcloggerinstance __=nullptD
then lock,
only

use
Kapil Yadav

Double checked
locking
-
: -

check for loggersrstance nullptr


= -

, if we
only
lock null,
need when
loggesirstance check
-_ =
a ,
so

this condition ,
because locks are
expensive .

linkedin.com/in/kapilyadav22
Kapil Yadav

[ ]

linkedin.com/in/kapilyadav22
Kapil Yadav

POINTS TO KEEP IN MIND : -

→ We want to astrict users to access the constructor


but there multiple
are
ways to access the
private
constructor

17 constructor
Make
copy as
private .

27 operator private
Make
equal to ,
overloading as .

From 01-1-11 we also need to use =delel= to


,

astrict to operations
uses
copy .

linkedin.com/in/kapilyadav22
Kapil Yadav

[ T-sxstn.cl
users

linkedin.com/in/kapilyadav22
Kapil Yadav

3 BUILDER DESIGN PATTERN : -

structure
→ whenever we are
building very complex
which has a lot
of configurations in it .

Builder Pattern that


"
construct
complex
says a

object from simple objects using step-by-step approach?


Kapil Yadav

Advantages of Builder
Design Pattern : _

clear
It provides separation between the construction

and
srepzesentation of an
object
.

better control construction


It
provides

over

process .

supports to
change the internal representation of

It

objects .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

4. OBSERVER DESIGN PATTERN : _

"
Pattern
just define
→ observer
An that one-to-one
says
states , all its
dependency so that when one
object changes
dependents are notified and updated automatically .

Ex -

group notifications .

linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav

5. Abstract
Factory Design :


Factory design pattern was
creating concrete classes
or
object .

create
→ Abstract
factory design pattern is
going to

factories that is
going
to coeale
object .

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav

linkedin.com/in/kapilyadav22
Kapil Yadav
Performance
Performance
Testing and its
Testing and its
value for startups
value for startups
For any new business coming in the market, it becomes
crucial for the technology to be,
- Resilient,
- Reliable,
- Stable and above all, something which gives
- Confidence to the customers.

Performance
Testing
This is the reason Performance Testing is a key factor for
us to evaluate the application and technology a startup
is basing its existence.
Stress
- Stress on Data
- Stress on Boundaries
- Requests and Responses
- User Load
- Transaction Load
- Internal Functions and APIs
Reliability
and Stability
- Data Updates and Handling
- Network handling
- Communication
- Speed of response
- Relevance of information
- Completeness of information
Failure and
Recovery
- Error handling
- Crashes and Shutdowns
- Help Tips and User Guidance during recovery.
- Backend Preventions and Support
User
Experience
- User understands the load and peak time constraints.
- Feedback loops
- System Navigation
- Third Party Experience and Reconnect
INTERNAL

1. Name the four main processes for creating and uploading a Power BI
report onto the Power BI Server.

This typically includes:

• Get and Transform Data, also known as Power Query, which involves
importing data and manipulating it.
• Data Modelling the data. This allows for adding calculated columns,
measures, and relationships between data sources.
• Adding data visualizations.
• Publishing onto the Power BI Service.

2. What are the main programs, apps, or options for buying or using
Microsoft Power BI?

• Power BI Desktop is the program in which you can create visualizations.


• Power BI Pro is a subscription-based service. It allows you to distribute the
content created with Power BI Desktop and upload it to Power BI Server,
Microsoft’s cloud-based server.
• Power BI Premium is a dedicated cloud-based server.
• Power BI Mobile is an app for your mobile device.
• Power BI Embedded allows you to embed your data analysis into your own
applications.
• Power BI Report Server is a non-cloud service, installed onto your servers.

Data Visualization questions


These questions cover the various visualizations possible in Power BI and how you
can customize them to display the analysis you want.
INTERNAL

Power BI visualizations

3. What are the differences and similarities between a table and a matrix
visualization?

Both tables and matrixes show data in a text format, similar to a spreadsheet.

Note that the plural of “matrix” in Power BI is “matrixes” rather than “matrices.”

Tables can show one row for each source table row. Both tables and matrixes can
show aggregated values (such as SUM, COUNT, MIN, or MAX).

A table shows one column for each field used. So if you have six fields included in a
table, there would be six columns.

A matrix is equivalent to an Excel PivotTable, so the number of columns is variable.


If a matrix has four rows fields and one column field for a date which includes 10
different years, then you would have 14 different columns when the years are being
displayed — 15 columns if you include the total. But if you drill down the column year
field to include quarters or months, the number of columns in the matrix changes.

4. What is the difference between drill down and drill through?

When you use Drill Down, you go to a different level of detail. For example, you may
be looking at a matrix that currently shows years. You can drill down so that the
matrix shows quarters or months. Or you could show the combination of years and
quarters and months.
INTERNAL

When you use Drill Through, you go from one report to another that concentrates on
some aspect of the first report. For example, you might click on a country in one
report, and drill through to a second report that concentrates on that country.

5. How can you add Drill Through to a report and how can you use it?

Suppose you wanted page A to drill through to page B.

You can add drill through by going to page B and dragging the relevant field to the
Add Drill Through Fields Here section.

You use Drill Through by going to page A, and then:

1. Clicking on the field you want to focus on

2. Going to Data/Drill —> Drill Through or right-clicking on the field and going to Drill
Through in the Context menu

6. What interactions can you have between different visualizations and


how can you control them?

The three interactions are: filter, highlight, and none.

Here’s how to control the interactions:

1. Go to Format —> Edit Interactions

2. Select a visualization

3. Select which interaction (filter, highlight, or none) you want to happen on the
second visualization

7. What are the three types of filters in Power BI?

The three types of filters are:

• Visual filters, which controls filters on one visualization


• Page filters, which filters all the visualizations on one page
• Report filters (also known as Filters on All Pages), which filters all the
visualizations on all pages

8. What visualization allows the end-user to apply a single filter over


several pages at the same time? And how can you configure which pages
it filters?

You can use a slicer, which allows you to filter on one page or multiple pages.
Configure which pages a slicer filters by going to View —> Sync Slicers.
INTERNAL

9. How can you show an invisible visualization?

Go to View —> Selection, which lists all the visualizations on the page, visible and
invisible. Toggle visibility for any visualization in this pane.

10. You set up a bar chart with the year in the X-axis and sales in the Y-
axis. How can you sort it so that the years are shown in sales order,
instead of year order?

By default, fields such as years are shown in a continuous sequence. For example,
2025 follows 2024 and is before 2026.

To show it in a different order, go to Visualizations —> Format —> X-axis, and change
Type from Continuous to Categorical. You can then sort the visualization by clicking
on More Options (the three dots in the top right corner of the visualization) and click
on Sort By —> Sales.

11. You have set up your page as you want to show it later. How can you
save this setup for future use? Name two ways you can retrieve it.

You can save your set up by using a Bookmark. Go to View —> Bookmarks and click
on Add.

You can also modify the bookmark so you can choose whether it remembers: the
Data, the Display, and/or the Current Page, and which visuals it remembers.

To retrieve your Bookmarks, you can go to View —> Bookmarks again and click on
the relevant bookmark. Or insert a shape, button, or another control with an Action,
and change the Action so that it goes to the relevant bookmark. This is a more user-
friendly way for the end-user to choose different bookmarks.

12. How do you add conditional formatting to a table?

To add conditional formatting:

1. Select the relevant field in a visualization

Data Visualization students also learn

Business Intelligence Microsoft Power BI Tableau Data

Science Data Analysis Data Modeling Data Mining Python R


INTERNAL

(programming language) Excel Machine Learning Business

Analytics SQL Excel Charts

2. Go to Visualizations —> Format —>Conditional Formatting —> Font Color (or


Background Color)

3. Switch this to On

You can then control the formatting by going to Advanced Controls within
Conditional Formatting.

Power Query questions


The next set of questions is about Get and Transform Data, which is also known as
Power Query. This shows a series of steps that you can use to manipulate data into
a better format for your visualizations.

Power BI Get and Transform

13. I’ve imported the data, but the wrong row is being used as the headers
— the row below should be used instead. What do I do?

The Applied Steps pane in Power Query shows the process that Get and Transform
Data uses. When you load data initially, then the computer adds a few steps
automatically. They typically include:

• Source – where you are loading the data from


INTERNAL

• Navigation – the specific data set within the Source


• Promoted Headers – setting the top row of the data as the headers
• Changed Type – changing the data type of the columns to a more specific
data type which still allows for all the sample data loaded in the column

However, if the first row was not meant to be used as the header (for example, there
is a title in the data set, and the headers are in the second row), then this can be
premature.

In the above example, to remove the Promoted Headers:

1. Remove the Change Type step (as Applied Steps should be removed in reverse
order)

2. Remove the Promoted Headers step

3. You can remove any Applied Steps by clicking on the x next to these steps

4. To remove any rows which should not be included in the data, go to Home —>
Remove Rows, and enter the number of rows to be removed

5. To Promote the new top row to be used as headers, go to Home or Transform,


then Use First Row as Headers

6. It’s a good idea to change the data types of your columns, most simply by
selecting all of the columns and going to Transform —> Detect Data Type (and
correcting any errors)

14. What is the name of the formula language used in Get and Transform
(or Power Query)?

It is called the “M” language (“M” is short for “Mashup”).

15. Name three ways to remove columns from your data

There are several ways to remove columns from your imported data. They include:
Right-click on a column or columns that you want to remove and select Remove.

• Go to Home —> Choose Columns. You can then uncheck columns you do not
wish to keep.
• Select the columns you want to remove and go to Home —> Remove Columns
—> Remove Columns.
• Select the columns you want to keep and go to Home —> Remove Columns —
> Remove Other Columns.
• Use the Table.RemoveColumns formula.

16. What is the difference between merge queries, append queries, and
combine files?
INTERNAL

• Merge queries allows you to introduce columns from one query into another
(or a new) query.
• Append queries allows you to introduce rows from one query into another (or
a new) query.
• Combine files allows you to load files on your computer and combine them
into a new query. The advantages of this include that these individual files
don’t have to become individual queries first and that you can simply point to
an entire folder as the source.

17. What is wrong with this M function: Table.transformcolumns?

M is case-sensitive. It should read: Table.TransformColumns

18. Name two different ways to convert a text column to date format.

Ways to convert a text column to date format include:

• Clicking on the ABC or ABC123 icon next to the field name and selecting Date
or Date/Time.
• Selecting the column and going to Home —> Data Type —> Date/Time.
• Selecting the column and going to Transform —> Date —> Parse.

The advantage of the last method is that it uses the DateTimeZone.From(_) formula,
which you can modify to change the locale. This is useful if, for example, your
computer is set up in American date format, but the dates are shown in British
format. In this case, you can modify the DateTimeZone.From formula to include the
fact that the dates are in the British format.

19. How do you use hard code the date 2 March 2024 in a formula?

You would use #date(2024,3,2). Make sure that “date” is all in lower case letters.

20. What is the quickest way to create a list of dates from 1 January 2022
to 31 December 2022 with every date included?

The quickest way to create a list of dates is:

1. Go to Home —> New Source —> Blank Query


2. Type in the formula bar: =List.Dates(#date(2022,1,1),365,#duration(1,0,0,0))
and press Enter
3. Go to Transform —> Convert —> To Table and press OK
4. Then convert this new column in this query to dates by going to Home —>
Transform —> Data Type —> Date

21. What is Query Folding and what are its advantages?


INTERNAL

When loading data from SQL Server or similar databases, it is possible that Power BI
will interpret some of the Applied Steps that you enter by changing the initial SQL
Server SELECT statement. The advantages of this are:

• The processing of these steps is done in SQL Server.


• The number of columns and rows retrieved from SQL Server is typically
reduced.
• The data can be loaded more quickly, reducing processing time and
bandwidth requirements.

DAX Functions questions

Power BI DAX Modeling

22. When using DAX formulas, what is BLANK()? Give an example of when
you should use it.

BLANK() is the equivalent of NULL in other languages. It means that the answer is
nothing.

You should use it when using zero or an empty string would lead to the wrong result
in a later formula. For example, there is a difference between 0+1 and BLANK()+1, as
the latter results in BLANK() instead of 1.

23. Can you write a formula that returns the number 1 only if all of the
following are true: [Price] > 2, [Price] < 10, and [Price]<>5 ?

You can use the following formula: =IF(OR(OR([Price] > 2, [Price] < 10),
[Price]<>5),1,0)

Unlike OR in Excel, the OR function in DAX can only have two arguments. You have to
nest ORs if you want to have more than two arguments.
INTERNAL

24. Why shouldn’t you write the following DAX formula


=MID([Description],10,1) ?

This formula is meant to retrieve the tenth character in the field [Description].
However, unlike Excel, if you use this when [Description] is less than 10 characters
long, it will result in an error. This error will then cascade throughout the column,
meaning that the entire column will result in errors.

You should couple this formula with IFERROR, or IF and LEN, to trap this error.

25. What is the difference between a calculated column and a measure?

A calculated column results in an answer for each and every row in a query. A
measure results in one answer for each context in which it is calculated.

Because the calculated column needs to calculate an answer for each row, this
results in an increase in the processing power needed.

Some functions that you can use validly in calculated columns cannot be used in
measures, and vice versa.

26. Name 4 DAX rounding functions (these are functions used in


mathematics).

Some of the DAX rounding functions are:

• INT – gives the nearest whole number rounded down


• CEILING, FLOOR, and MROUND – rounds to the nearest multiple of
significance (for example, to the nearest 0.05), either up, down, or nearest
• ROUNDUP, ROUNDDOWN, and ROUND – rounds to a specified number of
decimal places (for example, to one decimal place), either up, down, or
nearest
• TRUNC – truncates the number, removing all digits after a certain point (e.g.
after the first decimal place)

27. What are the differences between RELATED and RELATEDTABLE?

Let’s assume that there are two tables, A and B, which may be data from different
sources, but are connected using a one-to-many relationship. For example, table A
could be a list of employees, and table B a list of their expenses, and a single
employee could have multiple expenses.

RELATED allows you to get a single value where the relationship goes from “many”
to “one” based on the current filter context. For example, you could add a calculated
column using the RELATED formula in table B to import an employee’s name from
table A.
INTERNAL

RELATEDTABLE allows you to get multiple rows where the relationship goes in the
opposite direction, from “one” to “many.” For example, you could add a calculated
column in table A using the RELATEDTABLE formula to get all the expenses.

RELATEDTABLE typically requires another function, such as SUM, to deal with the
multiple rows.

28. What is the difference between SUM and SUMX?

SUM totals (for example) a column in a table, based on context. So if the context is a
particular employee, then SUM could total all of the expenses for that employee.

SUMX allows you to do a calculation before totaling the column. For example, you
could multiply two fields together, such as the number of items by the unit price for
each item, before totaling the column.

29. What does the CALCULATE function do?

The CALCULATE function allows you to perform an expression based on a filter. For
example, you could calculate all of the expenses for a particular employee, but only
for a particular month.

30. If DueDate for a particular context is July 17, 2025, what period does
the formula DATESINPERIOD([DueDate],FIRSTDATE([DueDate]),-7,DAY)
retrieve?

As the number of days is negative, the period goes before the July 17, 2025 date.

However, it goes back for seven days inclusive, so the first date is July 11, not July
10. So the total period is July 11-17, 2025.

Power BI Service questions


31. In Power BI Service, what technically is a dashboard?

A dashboard is a series of visualizations taken from various Power BI reports. So


you can take a visualization from one report and another from a second report.
Therefore, dashboards can be used as a high-level summary.

While a report may be loosely referred to as a dashboard, the term “dashboard” has a
specific meaning in the Power BI Service.

32. What is the difference between a dashboard and a report in Power BI


service?
INTERNAL

• A report is a single piece of work, generally created in Power BI Desktop, and


uploaded to the Power BI Service. A dashboard contains extracts from many
reports and is created in the Power BI service.
• A report is generally based on a single data source or a set of related data
sources. A dashboard does not have any independent data sources, so it may
have many data sources based on its source reports.

33. What is a Power BI app?

A Power BI app is a packaged series of dashboards and reports that can be shared.

34. In what two places do you configure row-level security?

1. Create roles while you are editing in Power BI Desktop using DAX expressions.

2. After uploading it into the Power BI service, add Row Level Security to the Dataset.

35. How can you refresh data stored on Power BI when the data is stored
on your machine or network?

You should use a data management gateway. There are two different types:

• The on-premises data gateway should be used if you have multiple users
connecting to the data sources.
• The on-premises data gateway (personal mode) should be used if you have
one user connecting to sources.
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Project Quality Plan

T14-2305 – Darwin – New Henbury


School – Design Development and
Construction Project

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 1 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Table of Contents

1.0 PLAN DEVELOPMENT AND PROJECT DETAILS .......................................................................4


1.1 Revision ..................................................................................................................................... 4
1.2 Amendments .............................................................................................................................. 4
1.3 Project Information ..................................................................................................................... 4
1.4 Project Purpose ......................................................................................................................... 5
1.5 Scope of Work ........................................................................................................................... 5
2.0 INTRODUCTION .............................................................................................................................6
2.1 Referenced Documents ............................................................................................................. 6
2.2 Input Documents ........................................................................................................................ 6
2.3 Project Documents .................................................................................................................... 7
3.0 CONSTRUCTION PROGRAM ........................................................................................................8
4.0 QUALITY MANAGEMENT SYSTEM ..............................................................................................8
4.1 Project Quality Plan ................................................................................................................... 8
4.2 Procedures................................................................................................................................. 8
4.3 Inspection and Test Plans (ITP’s) .............................................................................................. 8
4.4 Project Safety and Environmental Management Plans ........................................................... 10
4.5 Specifications, Drawings & Programs ..................................................................................... 10
4.6 Control of Quality Records ....................................................................................................... 10
5.0 MANAGEMENT RESPONSIBILITY ...............................................................................................11
5.1 Policy and Commitment ........................................................................................................... 11
5.2 Quality System Planning .......................................................................................................... 12
5.3 Project Organisation ................................................................................................................ 12
5.4 Project Responsibilities ............................................................................................................ 12
5.5 Project Quality Objectives ........................................................................................................ 15
5.6 Management Review ............................................................................................................... 15
5.7 Frequency ................................................................................................................................ 16
5.8 Method of Review .................................................................................................................... 16
5.9 Contract and Project Reviews ................................................................................................. 17
5.10 Reporting of Results ................................................................................................................ 17
6.0 SUBCONTRACTOR MANAGEMENT ............................................................................................18
6.1 Subcontractor Responsibilities ................................................................................................ 18
6.2 Subcontractors Working on the Project ................................................................................... 18
6.3 Subcontractor Companies Engaged ........................................................................................ 18
6.4 Subcontractor Compliance ...................................................................................................... 19
6.5 Subcontractor Performance Assessment ................................................................................ 19
7.0 RESOURCE MANAGEMENT .........................................................................................................20
7.1 Project Activities & Organisations ............................................................................................ 20
7.2 Training & Competency ........................................................................................................... 20
7.3 Induction Training .................................................................................................................... 20
7.4 Specific Project Site Induction ................................................................................................. 21
7.5 Specific Project Visitor Induction ............................................................................................. 21
7.6 Facilities & Work Environment ................................................................................................. 21
8.0 PROJECT REALISATION ..............................................................................................................21
8.1 Project Planning ....................................................................................................................... 21
8.2 Client Related Processes & Communication ........................................................................... 21
9.0 PRODUCT IDENTIFICATION AND TRACEABILITY .....................................................................23

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 2 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

9.1 Testing Traceability.................................................................................................................. 23


10.0 DESIGN & DEVELOPMENT ...........................................................................................................23
10.1 Design Concept ....................................................................................................................... 23
10.2 Design Risk Assessment ......................................................................................................... 24
10.3 Design Development Phase .................................................................................................... 24
10.4 Documentation Phase ............................................................................................................. 24
10.5 Design Changes ...................................................................................................................... 25
10.6 Design Change Management Process .................................................................................... 25
10.7 Assessing the Impact of the Proposed Design Change .......................................................... 25
10.8 Approving or Rejecting Proposed Changes ............................................................................ 25
10.9 Completion Phase ................................................................................................................... 25
11.0 PURCHASING & SUBCONTRACTING ..........................................................................................26
12.0 CONSTRUCTION CONTROL .........................................................................................................26
13.0 CUSTOMER PROPERTY ...............................................................................................................26
13.1 Inspection and Testing ............................................................................................................. 26
13.2 Inspection, Measuring and Testing Equipment ....................................................................... 27
13.3 Handling, Storage, Packaging and Delivery ............................................................................ 27
13.4 Disposal of Site Products, Waste and Refuse ......................................................................... 28
14.0 DOCUMENT, RECORDS AND DATA CONTROL .........................................................................28
14.1 Control of Records ..................................................................................................................... 28
15.0 MEASUREMENT, ANALYSIS & IMPROVEMENT .........................................................................28
15.1 Monitoring Client Satisfaction .................................................................................................. 28
15.2 Monitoring Project Activities..................................................................................................... 29
15.3 Internal Audits .......................................................................................................................... 29
15.4 Control of Nonconforming Product .......................................................................................... 29
15.5 Analysis of Data ....................................................................................................................... 30
15.6 Corrective and Preventative Action ......................................................................................... 30
16.0 DEFINITIONS ..................................................................................................................................31
APPENDIX 1 – CONSTRUCTION PROGRAM ..............................................................................................32
APPENDIX 2 - HALIKOS QUALITY POLICY.................................................................................................33
APPENDIX 3 – DOCUMENT CONTROL REGISTER ....................................................................................34
APPENDIX 4 – PROJECT ORGANISATION CHART ...................................................................................41
APPENDIX 5 – SAMPLE ITP ..........................................................................................................................42
APPENDIX 6 –PROJECT INTERNAL AUDIT SCHEDULE ...........................................................................43

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 3 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

1.0 PLAN DEVELOPMENT AND PROJECT DETAILS


1.1 Revision
All amendments to this document are to be marked up in the Control Table. The issue of the amendment is
to be by the authorisation of the Project Manager.

1.2 Amendments
All amendments are to be acted upon by the holders of this document upon receipt of the amendment. The
plan will be finalised during the project launch and will be progressively reviewed and updated if required.

Revision

Date Details Section Page Approved By


Chris
Feb 2015 Initial Release for Tender All All
Giannikouris

Distribution

Date
Copy Holder Details
Issued
Chris Giannikouris Halikos Design Manager Halikos Pty Ltd April 2015
Connor Newble Senior Project Manager Halikos Pty Ltd April 2015
Brian Hogbin SEQ Compliance Manager Halikos Pty Ltd April 2015
Johnny McLaughlin Construction Site Manager Halikos Pty Ltd April 2015
Sharon Sutton SEQ Compliance Advisor Halikos Pty Ltd April 2015

Authorisation

Date: Version: Document Reference: Approved By:


April 2015 1 PMP-3-04 Connor Newble

1.3 Project Information


Project Name New Henbury School – Design Development and Construction Project
Project Number T14-2305
Dripstone Middle School - Corner of Trower Road and Henbury Avenue, Tiwi
Project Address
NT.
Project Start Date 31 March 2015
Project Completion 30 June 2016
AS4801 Certification Certification current till 8th May 2017
Federal Accreditation Accreditation till 23rd July 2017
Prepared By Brian Hogbin
Date Prepared April 2015
Postal Address GPO Box 1511 Darwin NT 0801
Contact Person Brian Hogbin [email protected]

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 4 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

1.4 Project Purpose


This Project is for the design, development and construction of a new Henbury School facility located in Tiwi
in the Northern Territory. This project will provide a more state of the art facility in order for the students of
the school to receive a higher level of care and support. The existing Henbury School is designed to care for
students with special needs and this concept will be carried through to the new school under construction.

1.5 Scope of Work


The project works comprise of:

 The construction and commissioning of a new school oval for the use of Dripstone Middle School in
accordance with the 'for construction' documents included with the Request For Tender (RFT);

• Construction and commissioning of the new playing oval;

• Design development and construction documentation including all approvals;

• Decommissioning of the existing playing oval is to commence only on completion of with the
permission of the Superintendent. and

 The design development, 'for construction' documentation and construction of the new Henbury
School in accordance with the Principal’s design and contractual documents. The works also
include all necessary statutory approvals, certifications, production of operational management
documentation, work as executed documentation and graphic representations as required to
convey the project intent to stakeholders.

The Superintendent shall consider and approve each stage and early works packaging before the Halikos
commences each stage. Such approval may be given after Halikos demonstrates to the Superintendent that
the Contractor’s design and construction methodology meets the requirements and quality required of the
RFT and associated documents.

The intention of such consideration by the Superintendent is further to ensure the existing Dripstone school,
its services, and the local community are not unduly disrupted or inconvenienced.

Halikos is not to proceed onto subsequent stages without such approval.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 5 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

2.0 INTRODUCTION
This Project Quality Plan prepared by Halikos sets out in detail all procedures the Project team shall
implement to manage its activities on and near the site. This Plan will be implemented and maintained
throughout the duration of the Project.

Halikos have proposed a Project Management team led by the Construction Manager and an experienced
Project Manager who has managed projects of similar size and complexity to this Project.

The Halikos Project Management Team selected for this project will consist of experienced personnel with a
demonstrated ability to manage the construction workforce and who have undertaken many design and
construction projects.

Bringing together a proven team who have previously worked together, and who are local Darwin residents,
eliminates many of the problems associated with project start-up and reduces the risk of mid-project staff
changes.

All of the personnel nominated are proven performers with regards to delivering construction projects to the
highest quality, on budget and on time.

Our project team have been working full time on this project during the tender period and have
comprehensive knowledge of this project’s objectives and challenges. The project team is currently available
and ready to immediately mobilise on to this project.

2.1 Referenced Documents


 AS/NZS ISO 9001:2008 – Quality Management System - Requirements

 AS/NZS ISO 9004:2009 - Managing for the sustained success of an organization -- A quality
management approach

 Halikos Pty Ltd POL-1-03 Quality Policy

 Halikos Pty Ltd PMP-3-01 Project Health and Safety Management Plan

 Halikos Pty Ltd PMP-3-04 Project Environmental Management Plan

 Halikos Pty Ltd Associated Procedures

Copies of all Legislation and relevant standards shall be held at the Project site.

2.2 Input Documents


 RFT number T14-2305

 General Conditions of Contract NPWC Edition 3

 NT of Australia Radiation Protection Act

 Guide to Traffic Engineering Practice – Part 5 Intersections at Grade

 Urban Road Design – Guide to the Geometric Design of Major Urban Roads

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 6 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 AS2890.1 Off Street Parking

 AS/NZS 3500.3 – Plumbing and Drainage Part 3

 The Building Code of Australia

 Managing Urban Stormwater, Soils and Construction – Vol 1, 4th Edition, Landcom

2.3 Project Documents


The following documents will be maintained for the project:

 Management Review records

 Records of contract and tender reviews

 Subcontractor records including quotes & transmittals, subcontract agreements, purchase orders,
instructions, payments, variations and correspondence

 Register of Subcontractors

 Delivery dockets and Invoices

 Records of inspections and tests and test results

 Suppliers and subcontractors compliance certificates

 Calibration register and calibration results

 Noncompliance reports

 Records of corrective and preventive action

 Audit records

 Training and competency records

 Permits and approvals

 Drawings and drawing registers

 Revisions to project documentation & transmittals

 Site Diaries

 Progress payment claims and contract variations

 Correspondence with all project stakeholders

 Construction programs

 Minutes of meetings

 Monthly progress reports

 Requests for Information

 Record of Defects

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 7 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 Relevant procedures and records (including site safety and environmental management)

Refer to the supporting Halikos document:

 PRO-4-02 Document and Data Control Procedure

3.0 CONSTRUCTION PROGRAM


Please refer to Appendix 1 of this document.

4.0 QUALITY MANAGEMENT SYSTEM


The Quality Management System for Halikos defines and identifies the Policies, Plans, Procedures and
templates used to ensure a consistent product output to the same exceptionally high standard every time
Halikos undertakes an activity, which in this case a Major Government Project. This plan is a steering
statement of intent used to identify the tools and resources required to comply with and exceed customer
expectations.

4.1 Project Quality Plan


This Plan is directly in relation to the intent described in ISO 9001:2008 – Quality Management System –
Requirements. Not only is this plan used as a directional resource for the Halikos Group, it is also an
enabling methodology for resourcing the responsibilities for the Project outputs.

This plan describes the unique requirements of this project and its application throughout the project
lifecycle. This plan will also be the prescribed mechanism for the quality compliance benchmark throughout
the project.

4.2 Procedures
Project procedures provide specific details for the management of the identified quality issues at the project
level, including any relevant forms or checklists. Project procedures will always be subject to evolutionary
change throughout the project lifecycle as the expected standard of service provision may change.

Project procedures are also used as the provision of compliance confidence within the Project itself. This
compliance confidence enables both the customer and Halikos to ensure all system targets are maintained
as enablers to the identified output of the Project.

Refer to the supporting Halikos document:

 REG-7-06 Controlled Documents Register

4.3 Inspection and Test Plans (ITP’s)


Subject to project requirements Inspection and Test Plans are prepared to identify, plan and provide a record
of project specific inspections and tests from project commencement to completion. Although ITP’s are a
control mechanism for the activity being undertaken to ensure quality of product is met, this quality control
function will form part of the standard of evidence required to fulfil the customers confidence in service
provision. A sample ITP is detailed at Appendix 5 to this document.

As a minimum all ITP defined in the Tender Documentation shall include:

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 8 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

As a minimum, Halikos shall include ITP’s for:

 Site survey and set out;

 Site preparation and excavation;

 Concrete construction activities, inclusive of vapour barriers/membranes and sealing of penetrations;

 Structural steel construction works supply, storage and installation;

 Insulation and vapour barriers supply and installation;

 Roofing supply and installation;

 Doors and windows supply, storage and installation;

 External Cladding supply, storage and installation;

 Hydraulic works installation and testing/certification;

 Electrical works installation and testing/certification; and

 Mechanical works installation and testing/certification.

The following information is to be included in ITP's:

 Date;

 Product concerned;

 Name of sub-contractor, if applicable;

 When sub-contractors' ITP’s are required, verification of their compliance with the specified
requirements;

 Where each inspection and test point is located in the process;

 Who carries out the inspection or test;

 Characteristics to be tested;

 Method of inspection or test;

 Specified acceptance criteria;

 Hold points and witness points;

 Where lots or batches will be used;

 Form of record of results;

 Frequency and timing of the test; and

 Details of what is to be inspected.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 9 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

4.4 Project Safety and Environmental Management Plans


The Halikos Pty Ltd Safety and Environmental Management Systems (EMS) are comprised of various
elements. The Project Safety and Environmental Management Plans are an integral part of the quality
management system and will ensure that Halikos operates within a safe working environment and in an
environmentally responsible manner in accordance with Company policies and as required by the relevant
Northern Territory Acts and Regulations and customer requirements.

4.5 Specifications, Drawings & Programs


Versions of specifications, drawings, and project programs are all controlled electronically on the company
computer system. This project specific data is classified as technical data and will be managed in a
catalogued manner throughout the project.

4.6 Control of Quality Records


Records will be established and maintained to provide evidence of conformity to requirements and of the
effective operation of the quality management system. Records shall remain readable, accessible and
maintainable. The Halikos “Document & Data Control” procedure provides guidelines to effectively manage
these documents. Documents to be used in this project are listed in appendix 2.

Halikos maintain project records to provide evidence of compliance to requirements in accordance with
written procedures. Electronic records are protected by a backup system. The computer system is run from
an Uninterrupted Power Supply.

Documents required by the quality management system shall be controlled. Records are a special type of
document and shall be controlled according to the requirements stated in this sub-section.

A documented procedure has been established to define the controls needed to:

 Approve documents for adequacy prior to issue;

 Review and update as necessary and re-approve documents;

 Ensure that changes and the current revision status of documents are identified;

 Ensure that relevant versions of applicable documents are available at points of use;

 Ensure that documents remain legible and readily identifiable;

 Ensure that documents of external origin are identified and their distribution controlled; and

 Prevent the unintended use of obsolete documents, and to apply suitable identification to them if
they are retained for any purpose.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 10 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

The constitution of a Quality Record is as follows:

 Records of management reviews or minutes of meetings;

 Records of contract and tender reviews;

 Purchase orders;

 Registers of sub-contractors;

 Records of sub-contractor performance;

 Delivery Dockets;

 Invoices;

 Completed ITP’s;

 Test Results;

 Supplier’s and sub-contractor’s compliance certificates;

 Calibration schedules;

 Noncompliance reports;

 Records of corrective and preventative action;

 Records of audits, both internal and external; and

 Training records.

During the Project, Halikos shall make all quality records available to the Superintendent at all times during
normal working hours when requested to do so. To that end, Halikos shall (within one calendar month of date
of practical completion) provide a register of all quality records held.

Halikos shall retain all quality records for at least five years from the date of Project completion.

Refer to the supporting Halikos document:

 PRO-4-02 Document and Data Control Procedure

5.0 MANAGEMENT RESPONSIBILITY


5.1 Policy and Commitment
Halikos senior managers understand the vital importance of quality to the company’s continuing success.
Management therefore accepts total responsibility for setting a clear company policy for quality and for
providing resources to put the Policy into practice. Company Quality Objectives are communicated to all
workers through regular induction, reporting and project meetings.

The Halikos Quality Policy is included in appendix 1 of this plan. The Policy has been formulated with regard
to Halikos organisational aims and the needs and expectations of its clients.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 11 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Copies of the Quality Policy will be displayed at all Halikos offices. All workers are instructed in the Quality
Policy and their roles and responsibilities in the Quality System at initial induction and through regular
communication.

Refer to the supporting Halikos document:

 POL-1-01 Halikos Occupational Health and Safety Policy

 POL-1-02 Halikos Environmental Policy

 Pol-1-03 – Halikos Quality Policy

5.2 Quality System Planning


Quality planning for this project is performed during the tender stage by the Quality Management
Representative and the Project Quality Representative. On award of the contract, a project launch is
conducted and detailed quality planning is performed in accordance with the “Project Launch” and “Project
Documentation & Control” procedures.

Refer to the supporting Halikos document:

 PRO-4-52 Project Launch Procedure

5.3 Project Organisation


Halikos Pty Ltd is structured into operating in two distinct areas of operation, these being; Operations and
Projects. Functional reporting within Halikos Pty Ltd with respect to quality is summarised as follows:

 At Operational level, the Project Manager (or delegated staff member) is the Quality Manager
Representative (QMR) and has overall responsibility for Quality; Safety and Environmental functions
of the Halikos Group, these functions are managed at the Halikos Company Headquarters.

 At Project level, the Construction Site Manager (or delegated staff member) is The Project Quality
Manager Representative (PQMR) and has overall responsibility for Quality, Safety and
Environmental functions of Halikos Pty Ltd on the Project. The PQMR reports directly to the QMR.

 Fundamental checking by site supervisory staff and site based subcontractors will also be a feature
of the PQP. Placing responsibility for the achievement of quality objectives at the workface will lead
to greater accountability at this level.

The proposed organisation structure for the Project is detailed in Appendix 3.

The duties and responsibilities of Halikos staff are defined in position descriptions maintained by the Human
Resource Manager at the Halikos Company Headquarters.

5.4 Project Responsibilities


The duties and responsibilities of key personnel with respect to quality management on this project are
described below:

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 12 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Project Director/Manager:

 The Project Manager has overall authority in the determination of all matters affecting the
implementation and operation of the project. The Project Manager reports directly to the
Construction Manager.

The Project manager is responsible for:

 Reviewing and authorising the Project Quality Plan (PQP), and other project plans;

 Assigning quality responsibilities to all project personnel;

 Ensuring all project personnel are suitably trained, and possess the necessary skills to undertake
their designated quality responsibilities;

 Continually monitoring of quality performance to ensure compatibility and continued effectiveness


with the Company’s policy and objectives;

 Communicating quality performance to the Construction Manager;

 Providing sufficient funds, materials and equipment to ensure the PQP objectives are achievable;

 Participating in the review of the quality system and other relevant quality meetings and programs;

 Providing appropriate training in quality to all project personnel.

Project Quality Management Representative (PQMR)

 The PQMR is responsible for the implementation of the Project Quality Plan (PQP). The PQMR
reports directly to the Project Manager and has a reporting function to the Quality Manager
Representative.

The PQMR has the authority to resolve all quality assurance matters in conjunction with the Project
Manager. The PQMR has the authority to reject non-conforming products/processes and the responsibility
to ensure that remedial measures are implemented to curtail further non-conformance.

The PQMR is responsible for:

 Ensuring the Project Quality Plan is correctly implemented to meet the requirements of the project;

 Allocating project staff to perform inspections duties;

 Ensuring non-conformance is reported;

 Ensuring a non-conformance is dispositioned within the required time-frame and that


disposition/remedial solutions are effectively implemented;

 Reviewing inspection reports are ensuring any actions required are initiated;

 Ensuring subcontractors fulfil their quality system obligations;

 Attending meetings called to discuss quality issues;

 Identifying and documenting quality system problems;

 Assisting with the updating of the Project Quality Plan;

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 13 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 Reviewing and approving Inspection and Test Plans, Project Forms/Checklists;

 Liaising with the quality assurance representative from the client;

 Assisting in the auditing/assessment of suppliers/subcontractors

Verification and Validation Personnel (Generally Site Supervisors)

Verification Personnel are responsible for inspecting and testing works in accordance with the Inspection and
Test Plans. Such work shall include off-site manufacture and fabrication and onsite works.

Halikos has a qualitative measure for Verification and Validation and they are defined as:

 Customer Validation - The assurance that a product, service, or system meets the needs of the
customer and other identified stakeholders. It often involves acceptance and suitability with external
customers.

 Internal Verification - The evaluation of whether or not a product, service, or system complies with a
regulation, requirement, specification, or imposed condition. It is often an internal process.

Verification Personnel have the authority to reject any nonconforming product/process and are answerable to
the PQMR in this regard. Various project personnel with relevant experience/qualifications will be used to
perform the necessary inspections to ensure the quality of product is being upheld.

Verification Personnel are responsible for:

 Performing the inspection and testing, or witnessing the inspection and testing by others, as laid
down in the Inspection and Test Plans including release of Halikos nominated Hold Point;

 Preparing records of inspection/tests and making these available to the PQMR;

 Verifying that the procedures being used are adequate for effective control of quality;

 Rejecting defective workmanship and materials;

 Ensuring and verifying corrective action is taken when nonconforming work is identified.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 14 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

5.5 Project Quality Objectives

Principle - Customer Satisfaction:


 QMS Objective 1.1;

o The “Halikos, Construction Office” shall maintain customer focus by satisfying current and
future customer needs. Customers can be both internal and external to the organisation.

 QMS Objective 1.2;

o The “Halikos Construction Office” shall measure customer need satisfaction by means of a
validation process.

 QMS Objective 1.3;

o The “Halikos Construction Office” shall strive to meet customer expectations with due regard
to cost, schedule, technical, programmatic and supportability facets of risk mitigation.

Principle 2 - Compliance with Requirements, Procedures and Methods.


 QMS Objective 2.1;

o The “Halikos Construction Office” staff shall adopt a process approach to achieve a
consistent methodology of operation.

Principle 3 - Continual Improvement


 QMS Objective 3.1;

o Continual improvement of all quality policy principles shall be pursued through the review
and audit of the “Halikos Construction Office” and ‘Halikos Operational Projects’ processes.

5.6 Management Review


The Project quality system shall be reviewed as part of the project management and Halikos senior
management meetings. The Project Health and Safety Plan shall be regularly reviewed and updated in
accordance with the Review and Continuous Improvement Procedure. The SEQ Compliance Officer is
responsible for ensuring the continuing suitability and effectiveness of the Project system. Any new
occupational health & safety hazards, system improvements and results of audits identified during the
demolition and construction phase are to be communicated to all relevant workers, subcontractors and other
project parties. The Project Manager will authorise the Project Plans and any updates once demolition and
construction has commenced. Halikos senior management is required to monitor Workplace Health & Safety,
Environmental and Quality activities throughout the company. This will be done by consultation, meetings,
site visits and review processes. Halikos senior management must have an understanding and involvement
in resolving and preventing significant Workplace Health & Safety and system issues with the aim to prevent
fatalities, serious injuries, illnesses, accidents and incident, non-compliance. Halikos management will review
the Workplace Health & Safety, Environmental and Quality Management Systems to ensure that the systems
meet industry and legislative requirements and the company’s objectivises set out the system policy. The
project has dedicated a management position to oversee all responsibilities, including reporting on the

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 15 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

management system to the Managing Director and the Halikos’ senior management group. This position will
be held by the Safety Environment and Quality Manager.

Refer to the supporting Halikos document:

 PRO-4-01 Management System Review Procedure

5.7 Frequency
The Management System Review meetings should be conduct as per the FRM-6-55 Integrated Management
Systems Planner, or as required. The system will be reviewed on a six monthly basis, at a minimum annually
to ensure information is communicated effectively throughout the company and any changes to legislation,
codes of practices or industry best practice are adopted and implemented. The Managing Directors
directives can be documented and implemented across the group to ensure they reflect those legislative
requirements. The SEQ Manager will meet with the Managing Director once a month to discuss and action
company SEQ matters.

Refer to the supporting Halikos document:

 FRM-6-55 Integrated Management Systems Planner

5.8 Method of Review


The SEQ system method of review will be as the key agenda items formatted on the meeting review form
template. All aspects of the system will be reviewed with the focus on past safety, environmental and quality
performance and setting performance indicators for the following period. The senior management team sets
timeframes for implementation of the system. The review of company policies, objectives and procedures will
be performed, corrected and reported on by the SEQ Manager.

The review will include:

 Results from audits;

 The extent to which objectives and targets have been met;

 The continuing suitability of the Safety Management System in relation to changing conditions and
information;

 Concerns of relevant stakeholders.

All observations, conclusions and recommendations will be documented for necessary action.

The review will take into consideration, but not be limited to:

 Health and safety performance reports;

 Incident reports;

 Hazard identification;

 Statutory Workplace Health & Safety performance;

 Corrective action reports;

 Change to regulatory requirements;

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 16 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 Changes to Workplace Health & Safety standards;

 Community expectations and public interface.

5.9 Contract and Project Reviews


Senior management will review project specific Management System developed for the project. This will start
at tender by the SEQ Manager; once the project has started a review will take place in conjunction with the
Project Manager and SEQ Manager to assess project specifics and inclusions or omissions. This Plan
applies to all activities undertaken or proposed to be undertaken by the company. The Quality Plan will be
signed off and authorised by the Project Manager that is allocated overall responsibility for the project. It
clearly defines the roles and responsibilities of site management, subcontractors, and all workers on the
project. The Project Management System has expectations for Halikos senior managers to regularly visit the
site and discuss issues with site management and workers.

The Halikos Project Manager will be responsible for the development of a project deliverables register which
outlines all project deliverables required under the contract. The project deliverables register will be
implemented to manage procurement, registration, review and final submission of project deliverables prior
to uploading the web based computer application.

Pending the issue of a full set of contract documents for signature/sealing, the “Contract Issue Documents”
issued by the Client to enable the project to commence shall be reviewed by the Project Manager against the
“Tender” Documents as specified in Procedure PRO-4-52 ‘Project Launch’.

As part of the ‘Project Launch Procedure’ a Contractual Rights and Obligations summary will be undertaken
which is a summary of Client and Contractor obligations and protocols under the contract. Applicable
Contractual time bars are documented to ensure that contractual obligations are understood and executed in
a timely manner.

Refer to the supporting Halikos document:

 PRO-4-12 Tender and Contract Review Procedure

 PRO-4-52 Project Launch Procedure.

5.10 Reporting of Results


All review meetings will be minuted. All actions related to project specific sites will be raised as a
noncompliance and tabled at the site toolbox meeting. All findings from the review meeting that relate to the
workforce will be communicated through toolbox meeting, notice boards and safety meetings. Corrective
actions will be documented on the meeting minutes for action by those workers deemed responsible.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 17 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

6.0 SUBCONTRACTOR MANAGEMENT

To ensure all subcontractors engaged by Halikos are not exposed to identified hazards and are free from
risk, requires continual communication and consultation. Halikos is responsible for ensuring all workers
comply with current Legislation, Australian Standards, Codes of Practice and all Halikos Project
Management Strategies for the works performed. Halikos shall achieve this through a close working
relationship and ensuring there is a safe system of work for the task to be undertaken.

Refer to the supporting Halikos document:

 PRO-4-13 Management of Subcontractors Procedure.

6.1 Subcontractor Responsibilities

All Subcontractors are under the direction of Halikos, and shall participate in full with the Project Quality Plan.
Subcontractor workers are required to adopt the same responsibilities for Halikos workers. All
subcontractors will, in addition, report to the SEQ Compliance Officer, Project Manager, Site Manager,
Foreman and Supervisors for all matters relevant to Quality Assurance and Control on the project. Where the
subcontractor’s supervisor or manager is not physically undertaking work on the project they shall nominate
a Project Quality Management Representative (PQMR) who will be responsible for attending to their workers
issues raised at meetings and the day to day practices of their workers.

6.2 Subcontractors Working on the Project

All subcontractors shall be required to attend a Project Induction with the Halikos SEQ Compliance Officer to
discuss the specific elements of the Project Plan, hazards and risks, and the rules of the project.
Subcontractors shall also be required to submit (when required) Inspection and Test Plans and be involved
with specific activities that may be planned for the project. The task specific activities shall be determined in
consultation with Project Management. Whilst subcontractors will be required to submit Project Procedures
for particular work they propose to undertake on the project, they should be informed of the following:

Project Management acceptance and/or approval of a subcontractor procedure shall not in any way
remove or limit the subcontractor’s responsibility to provide and maintain as far as is practicable a
working environment that is safe and without risk to the health of workers, products and services
and the project program.

Refer to the supporting Halikos document:

 PRO-4-13 Management of Subcontractors Procedure.

6.3 Subcontractor Companies Engaged

At the start of any project the following process steps will be used to manage subcontractors and ensure
their compliance to work practices.

Refer to the supporting Halikos document:

 PRO-4-35 Subcontractors Selection Procedure.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 18 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

6.4 Subcontractor Compliance

Compliance will be managed through a review of work performed and scheduled audits to ensure
compliance is maintained with the work scope to be carried out on the project. Subcontractor supervision will
ensure that all workers and sole traders/subcontractors are, or have:

 Appropriate qualifications for the task to be under taken;

 Are insured by a third party or have their own insurances;

 Vehicles & mobile plant that meet Halikos’ and national standard requirements;

 Tools and equipment that meet Halikos’ and NT legislative requirements;

 Housekeeping that meets Halikos’ requirements;

 Permits to work (if applicable are provided).

6.5 Subcontractor Performance Assessment

All performance will be monitored and managed through project documentation, such as checklists.

Refer to the supporting Halikos document:

 PRO-4-13 Management of Subcontractors Procedure.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 19 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

7.0 RESOURCE MANAGEMENT


The adequacy of existing equipment and personnel resources and the need for new resources is identified
and reviewed regularly by the Project Manager.

Equipment and trained personnel are provided at all organisational levels to carry out the project processes,
verification as well as internal audits to ensure conformance to the project specification.

7.1 Project Activities & Organisations

ACTIVITY ORGANISATION
Architectural Design, review & analysis MKEA
Architectural Documentation MKEA
Building Supervision Halikos Pty Ltd
Progress Payment Certification Halikos Pty Ltd
Project Administration Halikos Pty Ltd
Structural Engineering W&G
Civil Engineering Byrne Design
Electrical Engineering NTBS
Mechanical Engineering Building Services Group
Hydraulic Engineering Building Services Group
Surveying Fyfe
Quantity Surveying N/A

7.2 Training & Competency


The Halikos training procedure provides guidelines and information to effectively manage the identification
and implementation of training needs. Where skill gaps in relation to specific requirements, licensing or
competency requirements are identified in the risk assessment process, workers will be provided with
information, instruction and training to provide them with the skills necessary to complete their task/s in a
safe manner. The Project Manager in conjunction with the SEQ Compliance Officer is responsible for
reviewing and maintaining the REG-7-20 Project Training Register and related records. Subcontractors will
be offered guidance on accredited training providers where training (as identified) can be undertaken.
Records of information, instruction and training provided to workers will be maintained onsite.

To ensure that staff are competent to perform their assigned tasks, the following systems have been put in
place:

 Position Descriptions including competency/education requirements

 Training is provided as determined by the position descriptions and performance reviews

 Job/quality requirements are communicated through Procedures

 A project “Training & Competency Matrix” will be maintained

The Halikos “Training” procedure provides guidelines and information to effectively manage identification and
implementation of Quality programs.

7.3 Induction Training


The Northern Territory government has implemented the, Code of Practice for Induction for Construction
Work. Prior to commencing work, Halikos will ensure workers have completed general induction training.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 20 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Halikos shall ensure that all workers hold a valid General Construction Industry Induction (White Card) and
appropriate licences for the task being conducted prior to commencing works on the Project.

7.4 Specific Project Site Induction

Prior to undertaking work on the project all workers will be required to undertake the Project specific Safety
Induction. The induction will include elements of the PSP, workplace specific hazards, and company policies,
procedures, and rules.

7.5 Specific Project Visitor Induction

Visitors and workers temporarily on the project to deliver plant, supplies, materials or services must report to
the project office and must receive instructions by the Site Manager or Project Manager. Depending on the
activities of the project at the time of the visit, and the nature of the visit the visitor may be requested to
undertake the project specific induction training detailed above. As a minimum all visitors to the project shall
be shown the emergency instruction sheet.

Refer to the supporting Halikos document:

 REG-7-20 Project Training Matrix

 Halikos Project Staff Position Descriptions

7.6 Facilities & Work Environment


Halikos will ensure that adequate facilities and a suitable work environment are provided to ensure that
workers are able to perform work in a safe and productive manner.

8.0 PROJECT REALISATION


8.1 Project Planning
Quality planning for this project is performed during the tender stage by the Quality Manager Representative
and the Project Quality Representative. On award of contract, a project launch is conducted and detailed
quality planning is performed in accordance with the “Project Launch” and “Project Documentation & Control”
procedures.

Refer to the supporting Halikos document:

 PRO-4-2 Document and Data Control Procedure

8.2 Client Related Processes & Communication


Once the Client has issued a full set of contract documents for signature/sealing, these documents shall be
reviewed by the Project Manager against the “Tender” documents to ensure that any deficiencies are
identified and are resolved with the Client. The Project Manager shall ensure that any matters affecting
design are transmitted to the Services and Coordination Manager for action as appropriate.

Any variation to the contract shall be reviewed by the Project Manager in conjunction with other project staff
with appropriate technical knowledge as required. The review is to ensure that technical and quality
requirements are clearly defined and that the project has the necessary resources, organisation and facilities
to perform its obligations under the terms of the variation.

All head contract variations shall be controlled via a register.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 21 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

Upon completion of the review, the Project Manager shall sign and date the variation, and ensure distribution
of the amendment to all concerned parties.

Refer to the supporting Halikos document:

 PRO-4-03 Consultation Procedure

Methods of communication include RFI (Request for Information) to Design Consultants and Site
Instructions to subcontractors. Client complaints shall be handled in accordance with the Halikos
“Noncompliance” procedure.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 22 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

9.0 PRODUCT IDENTIFICATION AND TRACEABILITY


Halikos shall establish and maintain documented procedures for identifying products from receipt to
construction, installation and delivery. Once the product has been identified using tagging, marking, or colour
coding this enables the product to be traced to its original source of procurement. The traceability of a
product can be undertaken in a number of ways:

 Serial number;
 Date;
 Code;
 Batch number; or
 Lot number.

Once a product has been identified (using the above method), the product is then to be placed where the
install of that item will eventually be, provided it does not obstruct any other works.

9.1 Testing Traceability


If testing is deemed necessary, all testing products, areas of the product install and test results are to be
identified so as to trace the origin of the product in its final destination.

10.0 DESIGN & DEVELOPMENT


The design approach for Halikos is to start with the project concept and planning phases with an emphasis
on making decisions about the design, materials used and methods of construction to enhance the quality
and safety of the project from start to finish. Where Halikos is involved in the design or has input into the
design, a documented risk assessment is to be undertaken at the design stage to identify, assess and
manage buildability issues that may arise during construction. Where Halikos is the head contractor and has
no input into the design, all design-related buildability hazards are to be identified, assessed and managed in
the pre-construction phase. The below process is to ensure design changes during the construction phase
are reviewed, assessed, documented and controlled. Any new hazards resulting from design changes during
the construction phase are to be communicated to all workers.

10.1 Design Concept

The responsibility for achieving a safe project design, are with those workers working on a project design and
development. This is achieved through consultation with workers who are directly involved in the design
activity such as architects, engineers, and those who make decisions that influence the design outcome. It is
started by establishing the design scope of the project. The risk management is defined by identifying the
scope of workplace hazards that need to be considered. Establish collaborative relationships with the client
and others who can influence the design outcome. Categorise the risks to be evaluated in areas such as
operational, technical, financial, legal, social, and environmental elements. Develop a safe design framework
for the project, by identifying the steps in the process that need to be taken to ensure that risks are
addressed throughout the course of the project.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 23 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

10.2 Design Risk Assessment

Managers involved in design activities should facilitate a design risk assessment with the design consultant
team. All consultants should identify design related hazards associated with the specifications that they
design with relationship to the completed project. The design and consultant team should assess the risks
arising from design-related hazards. All identified issues need to eliminate the hazards and control risks.
During the design concept phase, through the life of the design process, monitoring and review of the design
risk assessment and the risk control measures will continue. Halikos will maintain all records of design risk
workshops, risk assessments, and design meetings. Halikos will consult with all workers and consultants on
the project, and will provide significant updated information on the high risk design changes. The design risk
assessment must comply with the hazard and risk management process of this Plan and be referred to for
the standard as part of the process as it is undertaken.

10.3 Design Development Phase

The project designers need to consider risks relating to the construction and through to decommissioning of
a building which can be controlled by assessing them prior to designs and drawings being finalised. Key
design options need to be considered such as planning the disconnection and re-routing services and power
cables before the construction begins which will avoid contact by workers. Investigating and choosing
construction materials that are safe to handle and do not require special tools or resources. Allow for the
designing scope, the construction of temporary and permanent work platforms and stairways to help prevent
falls and other hazards from occurring during the phases of the design. Designing components which
facilitate the pre-fabrication off-site or on the ground to avoid the hazards associated with assembling or
erecting at height. Designers need to provide adequate clearance in the design between the building
footprint and power sources such as overhead power lines, and other electrical components. There must be
allowance for the erecting of construction equipment to be located on site such as cranes and other tall
equipment. It is critical that the design of parapets is to a height that complies with guardrail requirements,
eliminating the need to construct temporary guardrails during the construction. Work at height is considered
a high risk not just during construction, but must be considered for things such as roof maintenance.
Consideration needs to be made, if possible to reducing the space between roof trusses and battens to
reduce the risk of internal falls during roof construction.

10.4 Documentation Phase

The Halikos designer team and consultants will keep a record of the risks identified during the design
process and the steps taken to eliminate or minimise the risks. Records should be kept of new information
relating to all design modifications. The construction phase involves ensuring those records of risks are
available and reviewed by the project team. The design plans are a crucial document for Project Managers to
rely on for accuracy and ensuring that key project staff is following correct design plans. Monitoring and
evaluating the design risk controls is to be a regular activity of the project management team which done as
part of design meetings. Communication between the project management team and designers should
confirm the effectiveness of risk controls in the design. Hazard identification during the construction phase,
especially the identification of new hazards and risks encountered that were not previously known to the
designers should be communicated back for the improvement of the process. This process can be picked up
during toolbox meetings, safety compliance checks, and reported hazards from workers.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 24 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

10.5 Design Changes

All key Halikos and project stakeholders must assess all design change for potential risk. If there are no new
risks, that can be the end of the risk assessment process. If there are new risks identified, then Halikos’ risk
management process and procedure will be implemented.

Refer to the supporting Halikos document:

 PRO-4-15 Design Management Procedure.

10.6 Design Change Management Process

Whenever a key Halikos or project stakeholder determines that some safety aspect of the project should be
changed, then that stakeholder is to submit a change proposal to the project design team. The change
proposal should identify the work process in question, describe the aspect of the work process that the
stakeholder wishes to change, and include a description of the Workplace Health and Safety impact of the
proposed change.

10.7 Assessing the Impact of the Proposed Design Change

The design change proposal should be circulated to all key Halikos and project stakeholders who the
applicant has identified as being affected by the proposed design change. The design team will consider
circulating proposed changes with any other stakeholders for consultation. There will be involvement with the
project Workplace Health and Safety team on the possible Workplace Health and Safety effects of
implementing the proposed changes.

10.8 Approving or Rejecting Proposed Changes

Once the impact of the proposed change or changes has been assessed by all of relevant project
stakeholders, the project design management team should decide whether to recommend the acceptance or
rejection of the proposed change. The project design team may reject a proposed change if it is determined
that there are significant Workplace Health and Safety risks to project workers, construction workers,
maintenance workers or the end facility users and occupiers. The approval or rejection of a design change
will be done through the project design team meeting.

10.9 Completion Phase

The completion phase of a project will involve conducting a risk assessment for the safe receipt of the
completed project ready for handover to the client. The safe transfer of the completed project to the client will
be part of the completion and handover process. The communication of the residual risks and all risk control
measures that are implemented for the safety of users to the client.

Design will be performed by external Consultants as per the Halikos “Design Management” procedure.

Project Plans and procedures are updated as necessary as the design proceeds.

Refer to the supporting Halikos document:

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 25 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 PRO-4-15 Design Management Procedure

11.0 PURCHASING & SUBCONTRACTING


In accordance with RFT T14-2305 all subcontractors who are contracted to provide trade services valued at
over $100,000.00 must have industry accreditation. Subcontractors will be required to provide a nominated
PQMR for the extent of their tenure on the Project.

Additionally Halikos will endeavour to use local subcontractors and suppliers wherever possible, refer to the
project “Industry Participation Plan (IPP)”.

All purchased products (including subcontracted works) shall be subject to verification to ensure
conformance to contractual requirements.

The Project Manager shall review all purchase documents prior to approval and release. Halikos Position
Descriptions detail purchasing authority levels and responsibilities.

Halikos may arrange for offsite Inspectors to conduct inspection and verification activities at subcontractor’s
premises as required. The verification arrangements and the method of release shall be specified in the
purchasing documents.

12.0 CONSTRUCTION CONTROL


Identification and planning of manufacture/construction activities is detailed in “Process Control” procedure.

Qualification of personnel, equipment and procedures for these processes shall be in accordance with the
applicable Standards, Specification and Codes. Records of qualified processes, procedures, personnel and
equipment will be maintained in accordance with Halikos documented procedures.

13.0 CUSTOMER PROPERTY


The Principal will be responsible for the supply, delivery and installation of items described in of RFT T14-
2305.

13.1 Inspection and Testing


Inspection and testing of items and works shall be performed by authorised personnel as detailed in the
respective Inspection and Test Plan/checklist.

Product conformance will be determined by acceptance criteria laid down in the specifications and Inspection
and Test Plans.

During inspection and testing, any nonconforming product/process detected shall be identified, document
and segregated (where possible) in accordance with the Halikos “Compliance Control” procedure.

All manufactured/constructed items shall undergo final inspection and testing in accordance with specified
contractual requirements prior to release to the client. No manufactured/constructed items shall be offered to
the client until all the activities specified in the Project Quality Plan or documentation procedures and
instructions have been satisfactorily completed.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 26 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

All Laboratory testing is to be conducted by National Association of Testing Authorities (NATA) certified
organisations as defined in T14-2305 Tender Documentation.

Refer to the supporting Halikos document:

 PRO-4-18 Inspection Testing and Measuring Procedure

 PRO-4-06 Compliance Control Procedure

 PRO-4-02 Document and Data Control Procedure

13.2 Inspection, Measuring and Testing Equipment


All inspection, measuring and testing equipment (including newly acquired test equipment) used for
inspection and acceptance purposes, whether owned by Halikos, provided by the client or on loan, shall be
controlled calibrated and maintained in accordance with the “Monitoring and Testing Equipment” procedure.

For this project the following inspection, measuring and test equipment shall be subject to calibration:

Equipment Calibration Frequency Calibration Authority


Dumpy/Laser 1 month External
Theodolite 3 months External

The PQMR shall verify all test results and maintain calibration records on the project file.

Any equipment identified as having doubtful accuracy or precision shall be removed from use and calibrated.
Where any inspection, measuring and test equipment is found to be out of calibration, the validity of the
previous inspection results will be assessed and documented.

Refer to the supporting Halikos document:

 PRO-4-18 Inspection Testing and Measuring Procedure

 REG-7-15 Calibration Register

13.3 Handling, Storage, Packaging and Delivery


All items are handled and stored in accordance with documented procedures to prevent damage and
deterioration. Designated storage and holding areas are nominated in the site layout plan. All handling,
storage, packing and delivery techniques are defined in the Project Induction Package and also form part of
the site rules. On a weekly basis, the SEQ Officer for the Project will conduct a site inspection which
encompasses, overall site safety compliance, Quality of Product inspections, Environmental inspections and
storage of all items within the site boundary. The condition of all stock is periodically assessed during store
audits.

Refer to the supporting Halikos document:

 PRO-4-09 OHS Inspection and Testing Procedure

 PRO-4-10 Training and Induction Procedure

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 27 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 PRO-4-11 Internal Audit Procedure

 PRO-4-18 Inspection Testing and Measuring Procedure

13.4 Disposal of Site Products, Waste and Refuse


All disposal techniques are defined in PMP-3-03 Project Environmental Management Plan.

14.0 DOCUMENT, RECORDS AND DATA CONTROL


Documents required by the quality management system shall be controlled. Records are a special type of
document and shall be controlled according to the requirements stated in this sub-section.

A documented Halikos procedure (PRO-4-02 Document and Data Control Procedure) has been established
to define the controls needed to:

 Approve documents for adequacy prior to issue;


 Review and update as necessary and re-approve documents;
 Ensure that changes and the current revision status of documents are identified;
 Ensure that relevant versions of applicable documents are available at points of use;
 Ensure that documents remain legible and readily identifiable;
 Ensure that documents of external origin are identified and their distribution controlled; and
 Prevent the unintended use of obsolete documents, and to apply suitable identification to them if
they are retained for any purpose.

14.1 Control of Records


Records will be established and maintained to provide evidence of conformity to requirements and of the
effective operation of the quality management system. Records shall remain readable, accessible and
maintainable. Halikos procedures (PRO-4-02 Document and Data Control Procedure and PRO-4-08 Control
of Quality Records) have been established to define the controls needed for the identification, storage,
protection, retrieval, retention time and disposition of records.

Refer to the supporting Halikos document:

 PRO-4-02 Document and Data Control Procedure

 PRO-4-08 Control of Quality Records

15.0 MEASUREMENT, ANALYSIS & IMPROVEMENT


15.1 Monitoring Client Satisfaction
The Project Manager shall in conjunction with the team establish a mechanism to measure and monitor the
level of satisfaction/dissatisfaction within the Client’s team. Examples of issues to be monitored are Industrial
Relations, Progress, Quality, Safety, Environmental, Local Industry Participation, Indigenous Involvement
etc. A staff member shall be nominated by the Project Manager to establish the monitoring mechanism,
which shall include the recording, analysis, and reporting of data.

Refer to the supporting Halikos document:

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 28 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

 PRO-4-02 Document and Data Control Procedure

15.2 Monitoring Project Activities


Project activities (including subcontractor works) are monitored regularly in accordance with the relevant
Inspection & Test Plan/Checklists.

15.3 Internal Audits


“Internal auditing is an independent, objective assurance and consulting activity designed to add value and
improve an organisation’s operations. It helps an organisation accomplish its objectives by bringing a
systematic, disciplined approach to evaluate and improve the effectiveness of risk management, control and
governance processes.”

With the above in mind, the Halikos “Internal Audit Procedure” provides guidelines to effectively assess
project compliance against internal and external legislative requirements and identify causes of
project/system failures to promote proactive management of quality that result in continuous improvement
opportunities.

The nominated PQMR will implement the audit programme, schedule audit dates, and confirm names of the
audit team participants.

Project Quality Audits will be carried out at intervals defined in the Halikos audit schedule and will review
specific sections of the PQP to provide verification of the implementation, effectiveness and possible
recommendations for further improvement. The Audit Schedule is defined at Appendix 6 to this document.

The results of all audits shall be documented and Noncompliance Reports will be raised for deficiencies
identified and brought to the attention of the Project Manager for follow up action.

Following satisfactory rectification of the noncompliance and the identification and implementation of
corrective actions to prevent reoccurrence, the responsible person shall provide a completed copy of the
report to the auditor.

Refer to the supporting Halikos document:

 PRO-4-11 Internal Audit Procedure

 REG-7-19 Internal Audit Schedule

15.4 Control of Nonconforming Product


Any items that do not conform to specified requirements shall be prevented from inadvertent use or
installation. The “Compliance Control” procedure describes the process for identification, segregation (when
practical), classification, documentation, disposition and reinspection of the nonconforming product.

Where contractually required, concessions or waivers shall be sought from the client for the proposed use of
the product, which does not conform to specified requirements. All nonconformity shall be documented and
a register is maintained by the PQMR to monitor the status of the non-conformances.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 29 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

All products identified to be ‘Nonconforming’ shall be recorded on FRM-6-20 and isolated to ensure the
product is not used or installed inadvertently. Once FRM-6-20 is populated, the details of the noncompliance
are recorded on REG-7-24 within 24 hours (one working day). All products deemed to be Nonconforming
shall be identified to the Project Manager who has the overall authority and responsibility for remedial action
to be undertaken.

If amendment, variation or extension of time will result from the proposed remedial action, the Project
Manager will submit the Noncompliance report with the proposed remedial action to the Superintendent for
approval. Such a noncompliance constitutes a Hold Point and is to be noted on the ITP accordingly.

In the event of the Superintendent observing defective work or a defect in the quality system, Halikos will be
advised in writing. Within one ordinary working day of receipt of the advice, the Contractor shall raise a
noncompliance report and action it in accordance with Clause 7.4.13 of the Tender Documentation

Defects identified during the defects liability period will be documented and resolved in accordance with
Halikos procedures.

Refer to the supporting Halikos document:

 PRO-4-06 Compliance Control Procedure

 PRO-4-28 Servicing and Defect Liability Procedure

 FRM-6-20 Noncompliance Report

 REG-7-24 Action Register

15.5 Analysis of Data


Project Quality statistics shall be gathered on a regular basis using the standard report format.

Statistical information will be analysed and reported to all Halikos workers, project subcontractors and other
interested parties. The Project Manager will review project statistics regularly.

15.6 Corrective and Preventative Action


Halikos management ensures that the effectiveness of the quality system continually improves through the
use of quality system elements such as the Quality Policy, Quality Objectives, audit results, management
review meetings and the use of corrective action reports.

Corrective and/or preventative actions taken to eliminate the causes of actual or potential nonconformity
shall be in accordance with the documented procedure. The action taken shall be to a degree appropriate to
the magnitude of problems and the risks encountered.

Refer to the supporting Halikos document:

 PRO-4-06 Compliance Control Procedure

 PRO-4-02 Document and Data Control Procedure

 FRM-6-20 Noncompliance Report

 REG-7-24 Action Register

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 30 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

16.0 DEFINITIONS
Client - Department of Infrastructure, Construction Division.

Contractor - Halikos Pty Ltd.

Subcontractor - Any company or person who is contracted to Halikos Pty Ltd for the purpose of supplying
goods or services.

Consultant - The architectural and engineering consultants who have been engaged by Halikos Pty Ltd to
perform the design, preparation of detailed ‘For Construction’ documentation and necessary certification to
meet contractual requirements.

Project Quality Plan (PQP) - A document that describes how the work under the contract will be performed
and controlled, i.e. this document.

Procedure - A document which describes the method for undertaking a certain activity.

Inspection and Test Plan (ITP) - A document which describes what checks for compliance for a particular
process or activity are to be made.

Hold Point - A point in the construction or verification process beyond which work must not proceed without
the written approval of a designated person or authority.

Witness Point - A point in the construction or verification process at which an activity is to be observed.

Document: PMP-3-04 Revision: 1 Date: February 2015 Page 31 of 43


Document Owner: Construction Division Uncontrolled When Printed
Project Quality Plan
T14-2305 – Darwin – New Henbury School – Design Development and
Construction Project

APPENDIX 1 – CONSTRUCTION PROGRAM

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 32 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

APPENDIX 2 - HALIKOS QUALITY POLICY

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 33 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

APPENDIX 3 – DOCUMENT CONTROL REGISTER

1
Company Policies
Number Issue Name Reviewed Number Issue Name Reviewed
POL-1- Occupational Health & POL-1-
1 Apr-14 Free
01 Safety Policy 12
POL-1- POL-1-
1 Environmental Policy Apr-14 Free
02 13
POL-1- POL-1-
1 Quality Policy Apr-14 1 Personal Leave Policy Jun-11
03 14
POL-1- Workplace Violence POL-1-
1 Nov-12 Free
04 Policy 15
POL-1- Drugs & Alcohol POL-1-
1 Nov-12 1 Motor Vehicle Policy Jan-12
05 Policy 16
POL-1- POL-1-
1 Rehabilitation Policy Nov-12 1 Personal Leave Policy Aug-10
06 17
POL-1- Equal Employment POL-1-
1 Nov-12 Free
07 Opportunity Policy 18
POL-1- POL-1-
1 Sustainability Policy Mar-12 Free
08 19
POL-1- POL-1-
Free 1 Cash Holding Tills Jul-11
09 20
POL-1- POL-1- Contracts Agreements
Free 1 Jul-11
10 21 Leases Policy
POL-1- POL-1-
Free Free
11 22
2
Company Manuals
Number Issue Name Reviewed Number Issue Name Reviewed
Free Free
Free Free

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 34 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

3
Project Plans
Number Issue Name Reviewed Number Issue Name Reviewed
PMP-3- Project Health and PMP-3-
1 Dec-14 Free
01 Safety Plan 22
PMP-3- PMP-3- Industry Participation
Free 1 Dec-14
02 23 Plan
PMP-3- Project Environmental PMP-3- Project Training and
1 Dec-14 1 Dec-14
03 Management Plan 24 Education Plan
PMP-3- PMP-3-
1 Project Quality Plan Dec-14 Free
04 25
PMP-3- Project Emergency PMP-3-
1 Dec-14 Free
05 Response Plan 26
PMP-3- Cyclone Management PMP-3-
1 Dec-14 Free
06 Plan 27
PMP-3- PMP-3-
Free Free
07 28
PMP-3- Project Risk PMP-3-
1 Dec-14 Free
08 Management Plan 29
PMP-3- PMP-3-
Free Free
09 30
PMP-3- PMP-3-
Free Free
10 31
PMP-3- PMP-3- Indigenous
Free 1 Mar -15
11 32 Development Plan
PMP-3- PMP-3-
Free Free
12 33
PMP-3- PMP-3-
Free Free
13 34
PMP-3- PMP-3-
Free Free
14 35
PMP-3- PMP-3-
Free Free
15 36
PMP-3- PMP-3-
Free Free
16 37
PMP-3- PMP-3-
Free Free
17 38
PMP-3- PMP-3-
Free Free
18 39
PMP-3- PMP-3-
Free Free
19 40
PMP-3- PMP-3-
Free Free
20 41
PMP-3- PMP-3-
Free Free
21 42

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 35 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

4Procedures

Number Issue Name Reviewed Number Issue Name Reviewed


PRO-4- Management System PRO-4-
7 Dec-14 Free
01 Review 42
PRO-4- Document & Data PRO-4-
6 Dec-14 Free
02 Control 43
PRO-4- PRO-4-
6 Consultation Dec-14 Free
03 44
PRO-4- Legislative PRO-4-
6 Dec-14 Free
04 Compliance 45
Hazard Identification,
PRO-4- PRO-4-
8 Risk Assessment and Dec-14 Free
05 46
Control
PRO-4- PRO-4-
6 Compliance Control Dec-14 Free
06 47
Accident, Incident and
PRO-4- PRO-4-
7 Near Miss Dec-14 Free
07 48
Management
PRO-4- Control of Quality PRO-4-
3 Dec-14 3 Minor Purchasing Dec-14
08 Records Procedure 49
PRO-4- OHS Inspection and PRO-4- Subcontractor
6 Dec-14 3 Dec-14
09 Testing 50 Payment
PRO-4- PRO-4-
7 Training and Induction Dec-14 1 Tendering Dec-14
10 51
PRO-4- PRO-4-
1 Internal Audit Dec-14 1 Project Launch Dec-14
11 52
PRO-4- Tender and Contract PRO-4- Planning and
3 Dec-14 1 Dec-14
12 Review 53 Programming
PRO-4- Management of PRO-4- Temporary Works
6 Dec-14 1 Dec-14
13 Subcontractors 54 Design
PRO-4- Governance PRO-4- Completion and
1 Dec-14 1 Dec-14
14 Procedure 55 Handover of Works
PRO-4- PRO-4-
6 Design Management Dec-14 1 Position Description Dec-14
15 56
PRO-4- Tool and Equipment PRO-4-
4 Dec-14 Free
16 Management 57
PRO-4- PRO-4-
Free Free
17 58
PRO-4- Inspection Testing PRO-4-
3 Dec-14 Free
18 and Measuring 59
PRO-4- PRO-4-
Free Free
19 60
PRO-4- Electrical Isolation PRO-4-
5 Dec-14 Free
20 Management 61
PRO-4- Alcohol, Drugs and PRO-4-
4 Dec-14 Free
21 Smoking Control 62
PRO-4- Asbestos PRO-4-
4 Dec-14 Free
22 Management 63
PRO-4- PRO-4-
5 Working at Height Dec-14 Free
23 64
PRO-4- Plant and Equipment PRO-4-
5 Dec-14 Free
24 Management 65
PRO-4- Excavation and PRO-4-
5 Dec-14 Free
25 Trenching 66
PRO-4- Confined Space PRO-4-
5 Dec-14 Free
26 Management 67
Document: PMP-3-04 Revision: 1 Date: December 2014 Page 36 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

4Procedures

Number Issue Name Reviewed Number Issue Name Reviewed


PRO-4- Emergency PRO-4-
5 Dec-14 Free
27 Preparedness 68
PRO-4- PRO-4-
5 Injury Rehabilitation Dec-14 Free
28 69
PRO-4- Servicing and Defect PRO-4-
3 Dec-14 1 Corporate Identity Dec-14
29 Liability 70
PRO-4- PRO-4- Company Mobile
Free 1 Dec-14
30 71 Phone
PRO-4- PRO-4-
Free 1 Email and Internet Dec-14
31 72
PRO-4- PRO-4-
Free Free
32 73
PRO-4- PRO-4-
NCOP Dec-14 Free
33 74
PRO-4- PRO-4-
Free Free
34 75
PRO-4- Subcontractor PRO-4-
3 Dec-14 Free
35 Selection Process 76
PRO-4- Monitoring and PRO-4-
3 Dec-14 Free
36 Testing Equipment 77
PRO-4- PRO-4-
4 Precast Installation Dec-14 Free
37 78
PRO-4- Traffic Management PRO-4-
2 Dec-14 Free
38 Road Work 79
PRO-4- PRO-4-
Free 3 Accounting Timetable Dec-14
39 80
PRO-4- Mobile Crane Work PRO-4- Operation
5 Dec-14 3 Dec-14
40 Zone 81 Maintenance
PRO-4- Tower Crane Work PRO-4- Commissioning of
5 Dec-14 3 Dec-14
41 Zone 82 Works

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 37 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

6Forms and Templates

Number Issue Name Reviewed Number Issue Name Reviewed


Management Review FRM-6- Employee Personnel
FRM-6-1 1 Dec-14 1 Dec-14
Agenda 32 Details
Emergency
FRM-6- Monthly OHS
FRM-6-2 1 Management Plan Dec-14 1 Dec-14
33 Statistics Report
Checklist
Safety Plan
FRM-6-
FRM-6-3 4 Implementation Dec-14 Free
34
Checklist
Legislative FRM-6-
FRM-6-4 1 Dec-14 Free
Compliance Matrix 35
Project Organisation FRM-6-
FRM-6-5 1 Dec-14 Free
Chart 36
Matrix Of System FRM-6-
FRM-6-6 1 Dec-14 Free
Procedures 37
FRM-6-
FRM-6-7 Free Dec-14 1 Purchase Order Dec-14
38
Emergency Response FRM-6-
FRM-6-8 1 Dec-14 Free
Form 39
Emergency FRM-6- Hazard Identification /
FRM-6-9 1 Dec-14 1 Dec-14
Instructions 40 Assessment Control
FRM-6- FRM-6- Hazardous
Free 1 Dec-14
10 41 Substances Register
FRM-6- Injury Incident FRM-6- Safe Work Method
5 Dec-14 1 Dec-14
11 Notification 42 Statement (SWMS)
FRM-6- Management System FRM-6- Equipment Calibration
Dec-14 1 Dec-14
12 Review Minutes 43 Record
FRM-6- FRM-6-
Free Dec-14 Free Dec-14
13 44
FRM-6- Document Template - FRM-6- Electrical Equipment
1 Dec-14 1 Dec-14
14 Portrait 45 Register
FRM-6- Document Template - FRM-6- Plant Identification
1 Dec-14 1 Dec-14
15 Landscape 46 Register
FRM-6- Drawing & Document FRM-6- Lifting Equipment
1 Dec-14 1 Dec-14
16 Register 47 Register
FRM-6- Toolbox Meeting FRM-6- Confined Space Entry
1 Dec-14 1 Dec-14
17 Record 48 Permit & Checklist
FRM-6- Meeting Agenda & FRM-6-
1 Dec-14 1 Hot Work Permit Dec-14
18 Meeting Minutes 49
FRM-6- FRM-6- Fire Prevention &
1 Attendance Sheet Dec-14 1 Dec-14
19 50 Protection Form
FRM-6- Noncompliance FRM-6- Emergency Response
1 Dec-14 1 Dec-14
20 Report 51 Register
FRM-6- Noncompliance FRM-6- First Aid Injury
1 Dec-14 1 Dec-14
21 Register 52 Register
FRM-6- Accident Report & FRM-6- SWMS Assessment
1 Dec-14 1 Dec-14
22 Investigation Form 53 review
FRM-6- FRM-6-
Free Dec-14 Free Dec-14
23 54
FRM-6- FRM-6-
1 Audit Schedule Dec-14 Free Dec-14
24 55
OH&S Committee
FRM-6- FRM-6-
1 Audit Report Dec-14 1 Agenda & Meeting Dec-14
25 56
Minutes

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 38 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

6Forms and Templates

Number Issue Name Reviewed Number Issue Name Reviewed


FRM-6- Monthly Safety FRM-6- Notification Of OH&S
1 Dec-14 1 Dec-14
27 Checklist 57 Election
FRM-6- FRM-6- OH&S Election Ballot
1 Training Record Dec-14 1 Dec-14
28 58 Paper
FRM-6- Training & FRM-6- OH&S Representative
1 Dec-14 1 Dec-14
29 Competency Record 59 Nomination Form
FRM-6- Induction Attendance FRM-6- OH&S Representative
1 Dec-14 1 Dec-14
30 Register 60 Notice Of Results
FRM-6-
1 Site Induction Card Dec-14
31

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 39 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project

7Checklists and Registers

Number Issue Name Reviewed Number Issue Name Reviewed


REG-7- Legislative CL-7- Weekly Inspection
Dec-14 Dec-14
01 10 Compliance Register 01 1 Checklist
REG-7- Systems Evidence CL-7-
Dec-14
02 1 Register 02
REG-7- CL-7-
1 Man Hours Register Dec-14
03 03
REG-7- Site Inspections CL-7-
Dec-14
04 1 Register 04
REG-7- CL-7-
1 Inductions Register Dec-14
05 05
REG-7- Controlled Document CL-7-
Dec-14
06 10 Register 06
REG-7- CL-7-
1 Incident Register Dec-14
07 07
REG-7- Injury Statistics CL-7-
Dec-14
08 1 Register 08
REG-7- CL-7-
1 SWMS Register Dec-14
09 09
REG-7- Hazardous Substances CL-7-
Dec-14
10 1 Register 10
REG-7- CL-7-
1 Chemical Register Dec-14
11 11

REG-7- CL-7-
Emergency Response
Objectives and Dec-14 and First Aid Dec-14
12 12
3 Targets Matrix 1 Assessment Checklist
REG-7- CL-7-
1 Equipment Register Dec-14
13 13
REG-7- CL-7-
1 Scaffold Register Dec-14
14 14
REG-7- CL-7-
1 Calibration Regitister Dec-14
15 15
REG-7-16 1 PPE Register Dec-14
REG-7-17 1 Noise Register Dec-14
REG-7-18 1 Rain Gauge Register Dec-14
Internal Audit
Dec-14
REG-7-19 1 Schedule
REG-7-20 1 Training Matrix Dec-14
Training Participation Dec-14
REG-7-21 1 Register
REG-7-22 1 Mobile Plant Register Dec-14
WorkSafe Visit
Dec-14
REG-7-23 1 Register
REG-7-24 1 Action Register Dec-14
REG-7-25 1 LOTO Register Dec-14
REG-7-26 6 Project Risk Register Dec-14

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 40 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School – Design Development and
Construction Project

APPENDIX 4 – PROJECT ORGANISATION CHART

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 41 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School – Design Development and
Construction Project

APPENDIX 5 – SAMPLE ITP

Project: T14-2305 Henbury School Approved By: Date:

Key 1: W – Witness H – Hold S – Surveillance Attach Dockets, Certificates, QA Documents to ITP

Key 2: S/C – Subcontractor HA – Halikos Site QA Rep C – Client Site QA Rep BC – Building Certifier

DWG #: Item: Level: Grid Ref:

ALL ITP’s ARE TO BE SIGNED AND DATED ON THE ATTACHED ITP SIGN-OFF SCHEDULE

Verify or Test By Records/Remarks


Item Spec Activity (eg test frequency, reports, certificates, etc.)
Activity Name
No. Ref C
S/C HA
BC
1. Inspection Give sufficient notice so that inspection
may be made at the following stages:
- Film underlay installed on the base H W W
- Completed formwork and reinforcement, H W W
cores and embedments fixed in place.

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 42 of 43

Document Owner: Construction Division Uncontrolled When Printed


Project Quality Plan
T14-2305 – Darwin – New Henbury School – Design Development and
Construction Project

APPENDIX 6 –PROJECT INTERNAL AUDIT SCHEDULE

Document: PMP-3-04 Revision: 1 Date: December 2014 Page 43 of 43

Document Owner: Construction Division Uncontrolled When Printed


Jira Notes
Date: 07/06/2022

1)What is Jira?
● Jira is a tool to help your team manage work.

Author - Kanwar Dusaj


2)What is an Issue?
● An issue is a work item

3)What is a Project?
● A project is a collection of issues

4)What is a Board?
● A board is a visual display of work progress, often with 3-4 columns.

5)What is a workflow?
● A workflow is the path of statuses an issue will go through from start to finish.
An example of a simple workflow is an issue moving from To Do to In Progress to
Done.
2

6)What is a epic?
● An epic is a large initiative. Known as "parent" issues, epics contain smaller
issues within them. They often represent large bodies of work that can break
down into smaller tasks. It will be up to you and your team to decide what's a
large initiative and what's not.

7)What is a task?
● A task is the most common issue type. They contain a more detailed
description of a work item. Tasks can exist within a larger epic or exist all on their
own.

8)What is a story?

Author - Kanwar Dusaj


● A story is a feature or requirement from the user's perspective. Stories are
commonly used by software development teams. They define work items in
non-technical language.

9)What is a subtask?
A subtask is a further defined issue, used to break down tasks, stories, or bugs into
smaller work items. Subtasks must have a parent issue type. They cannot exist on their
own.

STAR POINT - Boards sit within projects. A single Jira project can have several boards. A
board is often named after a larger deliverable or team of people.
3

Different Boards in JIRA

Kanban boards
● Kanban boards are used by all types of teams. They illustrate a continuous flow
of work. Issues continuously move in and out of the board from the start of the
project until the end of the project.

Scrum boards
● Scrum boards are mostly used by agile software development teams. Scrum
boards bring in groups of issues that the team will attempt to complete during a
fixed period of time, often a two-week "sprint."

Author - Kanwar Dusaj


Golden Question -
What is agile? Agile is a project management methodology. It takes an iterative
approach to managing projects, focusing on continuous release that require regular
updates based on feedback. Agile helps teams increase delivery speed, expand
collaboration, and better respond to market trends. Learn more about agile here.

What is scrum? Scrum is a specific agile project management framework to help


design, develop, and deliver complex products. It's mostly used by software
development teams. Scrum teams organize their work in sprints. A sprint is a short,
fixed period when a scrum team works to complete a batch of issues. Learn more about
scrum here.
4

References

1) https://university.atlassian.com/student/collection/850385/path/1083901/activi
ty/1080730
2) KDTells ~ Confluence Certification Path – IT Quality Den (wordpress.com)

Author - Kanwar Dusaj


AAKASH SINGH TAHLAN
Contact: + 91-81683-69186
E-mail: [email protected] https://www.linkedin.com/in/aakashtahlan
Availability 1st Nov’ 23

21 + Yrs of Exp: Senior IT Consultant |CTL Prime QA & Testing and App Support Management, Delivery Management International Exposure
(On-Site): Cyprus (TSYS – 07-08), Jamaica (NCBJ 17-18, 21-22), and UAE (UNB- 18), India (ICICI- 22-23), Philippines (Aug 23- Till Date)

NOTEWORTHY HIGHLIGHTS

PERSONAL DETAILS Domains, Skills and Expertise


Current Location : Rohtak (Haryana), India
Language(s) : English, Hindi Domains:
Nationality : India
Software and Tools
• TS-Prime (CTL) Issuer and Acquirer • TS Prime
Notice Period : 30 days • BFSI/Credit Cards • Fraud Guard
• Ecommerce • Dispute Manager
• Online Steaming • My SQL
Summary • Online Recruitment • PL-SQL
Education and Certifications • HealthCare • Oracle 12 &19C
• SaaS • JIRA
• MCA & MSc Computer Science
Skills • MPP
• ISTQB – F • HP QC ALM
• Project Management
• Six Sigma Yellow Belt • Base Camp
• Support Management
• Remote Desktop
• Scrum Fundamental • Delivery & Release Management
• Amazon Workspace
• JavaScript Fundamental • QA and Test Management
• VTS
Expertise: • Module Testing • VSS
• Integration Testing • Crystal Report
Skilled in App Support management, Requirements Analysis, Stakeholder
collaboration, Project Monitoring and control, worked as Product SME, Developing • System Testing • MS Office
and Implementing Release and Configuration Management Process, Test planning, • Regression Testing • Google Docs
Test execution. Have a good understanding of Technical concepts, Implementing • User Acceptance Testing • Google Excel
strategies, Best Practices, Processes and Metrics Preparation, Business • Operational Acceptance Testing • Java/JavaScript
Communication & SCRUM Meetings, worked in Cards Reconciliation and
• Mobile Testing • C++
settlement project.
• .Net

Major Philippines Bank – Migration PMO Cluster Lead for Cards


✓ Planning and risk identification for Cards (TSYS) and Collections (Exus) during migration activities
✓ Preparing, execution and tracking Project plans using MPP, Project plan 365
✓ Communications management
✓ Stakeholders Management
✓ Red Flagging risks and blockers
✓ GO/NOGO clearance

ICICI India – App Support


✓ Currently working in TS-Prime 4 (CTL) App Support Manager (Consultant) with ICICI Bank, base location Hyderabad, mainly working on
Issuer Side, managing a team of 5 team members
✓ Responsible for tickets (defects raised with TSYS) management and coordinate with TSYS for swift closure of same
✓ Ownership of UAT testing and Production deployment for fix(s) received from TSYS
✓ TS Prime (CTL) Prime application L1 support management
✓ Knowledge of TS Prime (CTL Prime) 4 database and good at working with Oracle 12 and 19C
✓ Over 5 years’ experience in Cards Reconciliation and settlement projects
✓ Card Reconciliation Settlement Processer, Card System, General Files, reconciliation procedure, reconciliation of GL Accounts, Co-ordinate with
Card Center Reconciliation team, Cards and POS (point of sales) operations
✓ Scored excellent Project Performance ratings by managing project deliveries in a timely manner, maintained seamless cross-functional
coordination, met project deadlines and ensured SLA adherence.
✓ Managed overall UAT activities and secure sign-off(s) from stakeholders for implementation in production
✓ Provided world-class Project Management solutions as a Consultant to the client's ICICI Bank, India, Union National Bank, Abu Dhabi and
National Commercial Bank, Kingston Jamaica.
✓ Effectively implemented Burp suite (Security testing) and SQL injection validation (Penetration testing) for various projects.
✓ Spearheaded the technical functions efficiently by being involved in Data analysis and reconciliation, database tuning and SQL optimization,
Non-PRIME to PRIME data reconciliation and vice-versa.
✓ Testing batch processing on T-24 R15, identifying and back tracking issues
✓ Working closely with different functional team: Collections, Fraud Detection, Fee and Charges, Al Wifaq, RRAD, CSD, IT, Technical Support and Admin
teams
Annexure-A
PROJECT DETAILS Banking/Credit Cards (TSYS – CTL Prime) Domain Organization/Project

CTL – Prime 4 related Skills and Expertise


✓ Good understanding of Cards and Payments domain
✓ Good understanding of POS file processing (batch submission at merchant end)
✓ Good understanding of Token technology/Issuer and Acquirer to support and testing
✓ Good understanding of understanding on Auth and Clearing/Settlement lifecycle
✓ Well versed with digital wallets, mobile payments
✓ Good understanding of Merchant on boarding
✓ Good understanding of Switches and Payments infrastructure
✓ Good understanding of database knowledge (SQL or Oracle 12 and 19C)

Major financial institute Philippines (Aug’ 23 – Till Date)


✓ PMO cluster lead for Cards (TS-Prime) and Personal Loans (Exus) migration activities
✓ Reviewing and tracking MPP/Project plan
✓ Reviewing and ensuring timelines are being met according to project plans/MPP/Gant Chart
✓ Steering daily stand-up meetings and Triage calls
✓ Providing feedback(s) for decision making and steerco meeting
✓ Providing GO|NOGO recommendations

Industrial Credit and Investment Corporation of India (ICICI) Bank (May’ 22 – Jul’ 23)
✓ Ownership TS-Prime App-Support (Consultant)
✓ Ownership of working closely with ICICI Internal stakeholders and Vendor (TSYS)
✓ Ownership of Prime 4 tickets and co-ordination with vendor (TSYS) and internal teams
✓ Ownership to validate fix(s) provided by vendor (TSYS) in UAT and ensuring timely deployments on Production
✓ Ownership to offer support for critical incidents to internal (ICICI) teams and Vendor (TSYS) teams

National Commercial Bank of Jamaica (May’ 17-Mar’ 18, Mar’ 21-Mar’ 22)
✓ Amex and Discovery Payment Gateways
✓ Payment Facilitator
✓ Auto Settlement
✓ M-PoS Contactless
✓ Minimum Payment Alerts
✓ Chargeback Automation & Transactions Alerts

Union National Bank, Abu Dhabi, UAE (May’ 18 - Oct’ 18)


✓ Cards Auto Write-off and Provisioning Tool
✓ Worked closely with Cards Reconciliation and Settlement team

Sopra Steria (formally XANSA India) May’ 06 – May’ 08


✓ Barclaycard CAS-BAU
✓ Internet Instant Decision System (IID)
✓ BAID
✓ Cards Reconciliation and Settlement team

TSYS International May’08 – Mar’ 12


✓ Compliance

Synopsis: The BFSI project aimed at developing & testing Payment Systems like AMEX, MasterCard, and VISA issues mandates,
TSYS updates its products and provides updated versions to Client. TSYS applied these updates for its clients.

✓ TS – PRIME

Client: RBTT, ARVAL, B&S, CARF, ALRA, ICICI, DOHA


Synopsis: The BFSI project dealt with implementing clients’ requirements on the quarterly basis

ONSITE EXPEREINCE
➢ ICICI Bank, Hyderabad India – May’22 till Date
➢ National Commercial Bank, Kingston Jamaica as Consultant - Software Testing and Quality Analyst, Jul' 17-Feb' 18 & May' 21-Till Date
➢ Union National Bank, Abu Dhabi as Technical Advisor, Mar' 18-Oct' 18
➢ TSYS International, Jul' 08-Sep' 08 – Cyprus Nicosia
ORGANIZATIONAL EXPERIENCE
➢ SR intelligent Technologies May’22 – Till Date
➢ TSYS International as Sr. Test Lead - BFSI, May' 08-Mar' 12
➢ Steria (Formally XANSA India) as Test Analyst, May' 06-May' 08
➢ A1 Technology Pvt. Ltd., Delhi as Senior Test Engineer, Sep' 03-May' 06
➢ Treasury and Accounts Department Government of Haryana, Sep' 01-May' 03

CONSULTING EXPEREINCE – Offsite


➢ Software Testing and Quality Assurance Consultant, Dec' 12 - Mar’ 22
https://www.upwork.com/freelancers/~019a770a5b0cedf990
Number of Hours – 4029
Projects – 53
Key Clients
✓ SurfCode, US, Aug' 20-Aug’ 21
✓ VidCruiter, Canada, Oct' 13-Dec' 16
Annexures
Enclosed in Annexure-A (BFSI/Credit Card Domain)
TEST PLAN

AUG 25, 2022


Version History:

Version Revised By Summary Approval Date

Table of Contents
1. Introduction 3
2. Scope 3

3. Test Objective 4

4. Reference Document 4

5. Detailed Test Approach 4

Test Strategy

Test Schdeule

Problem Severity Classifcation:

Test Resources

Pass/Fail Criteria:

Environment

Test Cases and Test Scenarios


Tools and defect Tracking

Final Test Report

Exit Criteria

1. Introduction
The Test Plan outlines the scope, approach, resources, and schedule of all testing
activities. It identifes the items and features to be tested; types of testing. It contains a
detailed and executable strategy for conducting. It defnes the detailed testing objective
specifc to a particular system, the testing approach, test environment, test conditions, and
the test plan.

2. Scope
The scope of this test plan is to ensure websiteX meets all of its technical, functional and
business requirements. The purpose of this document is to describe the overall test plan
and strategy for testing the website. The approach described in this document provides the
framework for all the testing related to website. This document will also be updated as
required with the requirement updates. We also need to make sure that all the expected
results are achieved.

2.1. Out of Scope

3. Test Objectives
The general test objectives are to test the correctness of the generation of the
interface data fle, the content of the interface data fle, and any error conditions. The
quality objectives of testing the website are to ensure complete validation of the
business and software requirements:

Verify software requirements are complete and accurate


Perform detailed test planning
Identify testing standards and procedures that will be used while testing the
website
Prepare and document test scenarios and test cases
Manage defect tracking process
Finalize the prject for release

Reference Documents
—--------

5. Detailed Test Approach


Detialed testing phases and methodologies are mentioned below. We will follow the
protocols of each phase and achieve the highest results.

Requirement Analysis
Design Testing
Functionality Testing
Verify each functionlaity of the system is working as per requirement
Testing the links
Testing the forms
Cookies Testing
Validation (HTML/CSS/PHP)
Database Testing
Integration Test Specifcation
API Testing
Usability Testing
Compatibility Testing
Browser Compatibility
OS compatibility
Mobile browsing
Performance Testing
Load Testing
Stress Testing
Security Testing
Automation Testing
Smoke Testing
Beta Testing

5.1 Requirement Analysis


Requirements analysis is critical to the success or failure of a systems or software project
so we have to verify, validate and confrm each requirement. Requirements must be
validated on the basis of User Experience, User Interface, How to test the requirements,
Requiremnts are up to date.

Make sure the major scenarios and requirements are mentioned in the document. If there
is something missing, highlight the missing requiremnts and also suggest improvements if
there is any.

Analyze the following Requirements

—-----------

5.2 Design Testing


Test all the designs and verify all the designs must be correct as per the requirements.

And also make sure the designs for all the specifed languages and dark themes.

5.3 Functionality Testing


Test the functional requirements and determine every function of the software is acting in
accordance with the pre-determined requirements and tasks. At website, Performed
testing of all the links in web pages, checking the database connections, forms used in the
web pages for submitting or getting information from user & Cookie testing. Functional
testing is extended to the types given below.

5.3.1 Testing all the Links:


Test the outgoing links from all the pages from a specifc domain under test.
Test all internal links.
Test links jumping on the same pages.
Test links used to send the email to admin or other users from web pages.
Test to check if there are any orphan pages.
Lastly in link checking, check for broken links in all above-mentioned links.

5.3.2 Testing of the forms on the web pages:


Forms are the essential and integral parts of website . Forms are used to get information
from users and to keep interaction with them.

The following should be checked on the forms:

Check all the validations on each feld.


Check for the default values of felds.
Wrong inputs to the felds in the forms.
Options to create forms, if any, form delete, view or modify the forms.
Check that no empty forms are created.
There are different feld validations like email-id’s, user fnancial
information, date, etc
All the above validations should be checked in a manual or an
automated way.

5.3.3 Cookie Testing:


Cookies are small fles stored on a user machine that are basically used to maintain the
sessions such as the ‘login sessions’. Test the website to verify

Test the application by enabling or disabling the cookies in your


browser options
Test if the cookies are encrypted before writing to user machine
During the test for session cookies (i.e. cookies expire after the
sessions ends) check for login sessions and user stats after session end
Check effect on application security by deleting the cookies

5.3.4 Validation (HTML/CSS):


HTML/CSS validation is very important for optimizing the website for

search engines.

The site has full and correct Doctype


The site uses character set
The site uses valid XHTML
The site uses valid CSS
The site has no unnecessary ids or classes
The site uses well structured code
The site has no broken links
The site has clearly defned visited links

5.3.5 Database Testing:


Check for data integrity and errors while you edit, delete, modify the forms or do any
database related functionality.
Check if all the database queries are executing correctly and data is retrieved
correctly and also updated correctly.

Also we need to validate the Database by executing the queries.

Comp
5.4. API Testing
Set of procedures to verify the expected functionality, reliability, and security and ensure
the correct interaction between backend and frontend. To validate the logic of the build
architecture within a short amount of time. Each api test consists of some test actions
mentioned below. Further details of API Testing will be covered in API Test Plan

Verify the URL accordingly environment


Verify required request headers and their correct values
Verify response payload
Verify correct HTTP status code and response headers
Verify expected result and correct application state
Verify correct performance sanity

5.6. Usability Testing:


The goals of usability testing include establishing a baseline of user performance,
establishing and validating user performance measures, and identifying potential design
concerns to be addressed in order to improve the effciency, productivity, and end-user
satisfaction.

The usability test objectives are:

To determine design inconsistencies and usability problem areas within the user
interface and content areas.
Potential sources of error may include:
Navigation errors – failure to locate functions, excessive keystrokes to
complete a function, failure to follow recommended screen fow.
Presentation errors – failure to locate and properly act upon desired
information in screens, selection errors due to labeling ambiguities.
Control usage problems – improper toolbar or entry feld usage.
Exercise the application or web site under controlled test conditions with representative
users. Data will be used to access whether usability goals regarding an effective,
effcient, and well-received user interface have been achieved.
Establish baseline user performance and user-satisfaction levels of the use interface for
future usability evaluations.
Basic Usability:
The site should have a clear hierarchy.
Headings clearly indicate the structure of the document
Navigation should be easy to understand
Navigation is consistent throughout the site
The site uses underlined links
The site uses consistent and appropriate language
The site has easy to fnd sitemap and contact page
The site has a search tool
The site has a link to home page on every page
The site has clearly defned visited links

5.7. Compatibility Testing:


5.7.1 Browser compatibility
Some requirements are very dependent on browsers. Different browsers have different
confgurations and settings that the web page should be compatible with. The web site
coding should be cross browser platform compatible. Test the UI of website, functionality,
security checks or validations then stresses browser compatibility testing of the web
application. Test web application on different browsers like Internet explorer, Chrome,
Firefox, Netscape navigator, AOL, Safari, Opera browsers with different versions

5.7.2 OS compatibility:
Some functionality in the web application may not be compatible with all operating
systems. All new technologies used in web development like graphics designs, interface
calls like different API’s may not be available in all Operating Systems. Testing the web
application on different operating systems like Windows, Unix, MAC, Linux, Solaris with
different OS favors.

5.7.3. Mobile browsing:


Mobile browsing is also an integral part of browsing. Testing the web pages on mobile
browsers is highly important. Compatibility issues may be there on mobile. Currently ,the
system is not designed for mobile browsing, although this is an area we can add in future.

5.8. Performance testing:


Website should sustain heavy load. website performance testing should include: Load
Testing & Web Stress Testing. Test the website on different Internet connection speeds.

5.8.1. Load Testing:


Test website if many users are accessing or requesting the same page. Can the system
sustain peak load times? Site should handle many simultaneous user requests, large input
data from users, Simultaneous connection to DB, heavy load on specifc pages etc. For load
testing we will use blazemeter and robot scripts.

5.8.2. Stress Testing:


Generally stress means stretching the system beyond its specifcation limits. Web stress
testing is performed to break the site by giving stress and check how the system reacts to
stress and how the system recovers from crashes. Stress is generally given on input felds,
login and sign-up areas. In website performance testing website functionality on different
operating systems, different hardware platforms are checked for software, hardware
memory leakage errors. For stress testing we will use jmeter and blazemeter.

5.9. Security Testing:


Test by pasting the internal URL directly into the browser address bar without login.
Internal pages should not open.
If you are logged in using a username and password and browsing internal pages
then try changing URL options directly. I.e. while checking website Try directly
changing the URL site ID parameter to a different site ID, which is not related to,
logged in user. Access should be denied for this user to view others' stats.
Try some invalid inputs in input felds like login username, password, and input text
boxes. Check the system reaction on all invalid inputs.
Web directories or fles should not be accessible directly unless given
download option.
Inspect the pages and verify Elements, Console and Sources.
Test the CAPTCHA for automated script logins.
Test if SSL is used for security measures. If used proper message should
get displayed when the user switches from non-secure http:// pages to secure
https:// pages and vice versa.
All transactions, error messages, security breach attempts should get logged-in log fles
somewhere on the web server.
Check the security points while the communication between frontend and backend.
It may includes:
User IP

Accept-Language

SESSION_ID/Device ID

Signature

User-Agent
Furthermore we will use Zap for security testing. It is an end-to-end web application
security scanner. This will give us a 360-degree view of the security of our website. It
is important to have an understanding of how the client (browser) and the server
communicate using HTTP. the tester should at least know the basics of SQL injection
and XSS.

Automation Testing:

5.10. Automation Testing:


Automate all the implemented functinlaities of the website . Creation of the automation test
cases. Details of Automation testing will be discussed and covered inside the Test Plan of
automation testing.

Write the test cases in a test rail for specifc features.


Analysis of test cases which are possible to be automated
Plan the test cases and how to execute all the test cases.
Write the test cases w.r.t environment.
write the logic for how to validate the test.
Write the pass/fail criteria agaist each test case.
run and actually verify the test.
Integrate all the test cases of each feature/module

5.11. Smoke Testing:


Smoke Testing is a software testing process that determines whether the deployed
software build is stable or not. Insid the smoke testing QA Engineer will make sure all the
critical functionalities are working fne. We will create a checklist of smoke testing.

Smoke testing will be performed at two stages. Once new features are added, the other is
before fnalizing the build for Production/live.

Create the checklist for smoke testing.

5.12. Beta Testing


Beta testing is basically a relase for specifc users to use a product in a production
environment to uncover any bugs or issues before a general release.

Beta testing is the fnal round of testing before releasing a product to a wide audience. The
objective is to uncover as many bugs or usability issues as possible in this controlled
setting. QA will also a perfrom the beta Testing.
6. Test Strategy
The overall strategy of this testing initiative is manual, black box testing. We are
testing the data, interface part and mplemented system in detail. The testing at the
SAP end of the interface will be covered by the SAP functional testing. Follow the
testing phases and techniques mentioned inside “Detailed Test Approach”. All type
of testing are covered in this document.

Some of the test specifcations use test data which needs to be set-up in the test
environment prior to executing the test cases.

For each level of testing, a separate test plan is prepared with the following set of
deliverables:

Test Cases/Test Sceanrios


Features to be tested
Items to be tested
Pass / Fail criteria
Bugs cycle
Automation
Expected Results
Actual Results

Test Schdeule
The test schedule is the timeline of acceptance testing activities and deliverable dates.

Testing activities are mentioned below.

Requirement Analysis.
Design Testing
Develop test scenarios
Develop test cases
Review scenarios/test cases for accuracy, completeness and sequence (confrm
test data is correct)
Integration testing
API Testing
Regression Testing
Functionality Testing
Database Testing
Integration Test Specifcation
Usability Testing
Compatibility Testing
Performance Testing
Security Testing
UAT Testing
Automation Testing
Smoke Testing
Beta Testing

Problem/Bug Severity Classifcation:


The identifed severity for each problem implies a general reward for resolving it, and a
general risk for not addressing it, in the current release.

Severity 1 - Crash or High impact problems that often prevent a user/host from correctly
completing an experience/booking.

Severity 2 - Moderate to high frequency problems with the functionality/UI or UX impact

Severity 3 - Either moderate problems with low frequency or low problems with moderate
frequency; these are minor annoyance problems faced by a number of participants.

Severity 4 - Low impact problems faced by few participants; there is low risk of not
resolving these problems. Reward for resolution is typically exhibited in increased user
satisfaction.

9. Test Resources
Here is the list of resources with the roles those will work on website

1.
2.

10. Pass/Fail Criteria:


Create the test cases and mention the expected results/pass criteria against each testcase.

11. Environment
Start testing on a staging server once a certain level is achieved, then move to Production
and give the fnal approval at Production. All the experiments should be performed at
staging. Testing data must be private at Production.
12. Test Cases and Test Scenarios
Write down the detailed test cases on the basis of requirement, technical doecument and test
plan. For testcases use the Google sheet and use the Jira for bug, suggestion reporting.

13. Tools and defect Tracking

Jira wil be used for defect reporting and issue bugs/defects management and
traceability.

14. Final Test Report


Test closure reports shall be generated for each testing phase as the testing phase gets

completed.

15. Exit Criteria


All the test cases and test scenarios must be passed. Every user must get the music
recommendation as per their interests.
==============================================================================
Accenture QA Automation interview real time que.

• Can you brief me about yourself?


Hi, my name is Pankaj.

I started my career as a Testing Executive 4.5 years back with Infosys currently I am working as Test
Engineer.
My responsibility is to understand Business Requirement Specification and High-Level scenarios and to
convert them into test cases & Automation scripts if required.
Execution of test cases and reporting of defect to the developer if there any and get them fixed.
I have experience on Functional, Automation, Regression, Smoke, Sanity, Web accessibility, Web
Analytics, Mobile Testing.

In my previous project I have worked on Automation testing where we have used Selenium with java and
TestNG Cucumber framework for BDD approach. We have used Page object model where we have
separated our test cases with page objects, and we performed testing on the same. For build
management tool we are using Maven for version controlling we are using Git and for automating our
jobs for nightly run or any schedule we are using Jenkins,.

For defect management & test case management we have used JIRA, TEST RAIL & HP ALM.
I have worked on tools like BrowseStack, DeviceAnywhere, Toadsql,

I am working on Agile environment we have daily standup call and we have 2-week sprint cycle. I am part
of 8-member team out of which we are 3-Tester, 2- dev, 1- manager, 1-scrum master.

• Tell me your Day to Day activities as QA?

First thing I do after login in my system. I check the active sprint in Jira for our project code. There I can
see my assigned open tasks. After that I will check my mail if there is any important mail I need to take
action on. Then we have our daily scrum meeting where we used to tell our previous day actions what we
did, what we are planning for today and if we have any blocker to discuss. Product owner and scrum
master help us to resolve that blocker. After that I need to take the pending task and do needed action
whether creating test case, Execution, Defect retesting if any.

• Do you have created framework from scratch, or you have maintained that?
I have not created Framework from scratch by myself but yes, I was part of framework creation and
created some part of it.

• How much you rate yourself in Java out of 10?


Out of 10 I will rate myself 6 in java as QA Automation engineer.

• Can you tell me Oops concepts and relate it with your Framework?
We have Polymorphism, Inheritance, Encapsulation and Abstraction in Oops. So, we will start with
1) DATA ABSTRACTION
Data Abstraction means to handle complexity by hiding unnecessary details from the user. In java,
abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using
interfaces.
In Selenium, WebDriver itself acts as an interface. Consider the below statement:
WebDriver driver = new ChromeDriver();
We initialize the Chrome Browser using Selenium Webdriver. It means we are creating a reference
variable (driver) of the interface (WebDriver) and creating an Object. Here WebDriver is an Interface and
ChromeDriver is a class.
We can apply Data Abstraction in a Selenium framework by using the Page Object Model design pattern.
We define all our locators and their methods in the page class. We can use these locators in our tests but
we cannot see the implementation of their underlying methods. So we only show the locators in the tests
but hide the implementation. This is a simple example of how we can use Data Abstraction in our
Automation Framework.

2) ENCAPSULATION
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Encapsulation can be achieved by: Declaring all the variables in
the class as private and writing public methods in the class to set and get the values of variables.
All the classes in an Automation Framework are an example of Encapsulation. In Page Object Model
classes, we declare the data members using @FindBy and initialization of data members will be done
using Constructor to utilize those in methods.

3) INHERITANCE
Inheritance is the mechanism in java by which one class is allowed to inherit the features (fields and
methods) of another class.
We can apply Inheritance in our Automation Framework by creating a Base Class to initialize the
WebDriver interface, browsers, waits, reports, logging, etc. and then we can extend this Base Class and its
methods in other classes like Tests or Utilities. This is a simple example of how we can apply Inheritance in
our framework.

4) POLYMORPHISM
Polymorphism allows us to perform a single action in different ways. In Java polymorphism can be
achieved by two ways:
– Method Overloading: When there are multiple methods with same name but different parameters then
these methods are said to be overloaded. Methods can be overloaded by change in number of
arguments or/and change in type of arguments.
In Selenium Automation, Implicit wait is an example of Method Overloading. In Implicit wait we use
different time stamps such as SECONDS, MINUTES, HOURS etc.
– Method Overriding: It occurs when a derived class has a definition for one of the member functions of
the base class. That base function is said to be overridden.
In Selenium Automation, Method Overriding can be achieved by overriding any WebDriver method. For
example, we can override the findElement method
In assertion we have used overload because in assertion we used to like asset.true(actual, expected) and
second time we can use same assert.true(actual, expected, message).

• How can you use interface and how it is different from Abstract class?
Abstract class may have Abstract and concrete methods, and there is not any compulsion in adding
abstract method in abstract class. But in Interface, we do have only abstract methods and we don’t need
to write abstract keyword in Interface this is by default public and abstract.
• What do you mean by Static keyword in Java?
Static means it is at class level not at instance level, we have static method, static variable & static inner
class. When we have any variable as static so it will remain same for all the instance of our classes, and
static/Private/Final methods can’t be over-ridden like if we have initialized any method as Static so we
cannot override it in any child class.

• How to call static method and variable in java?

Direct calling, Calling by class name.

• Can I access Static method by using object reference?


Yes we can, but we got one warning that you need to access it via Direct or By class name.

• How to call non-static method and variable in java?


For calling non static method we need to create object first.

• Can we overload & override main method?


Overload-Yes, Override-No

• What do you mean by wrapper class and how will you do data conversion?
Wrapper class in java are used for data conversion. In data conversion if user wants to convert Int to
string, String to int, Boolean, double then we use Wrapper class.
integer.parseInt(); - To convert string to Integer
Double.parseDouble(); - To convert string to Double
Boolean.parse Boolean(); - To convert string to Boolean
String.valueof(); - To convert Integer to String.

• Can you convert string a =”110a” in integer?


No we got NumberFormatException while converting the above string.

• What do you mean by Call by Value & Call by Reference in Java?


Call by value means suppose we have created one sum method with input parameter int a, int b. So while
calling the creating the object and running we provide values that is know as call by value.

• What do you mean by Exceptions in Java?


Exception is like any interruption in our normal flow. Like if we are running anything and we got issues in
our script this is we called exception, we have 2 types of exception Run Time & Compile Time. (checked &
Unchecked exceptions)

• Can you tell me about difference between Throw and Throws keyword?
Throw is a keyword used inside a body of function. And Throws used while initializing any method. By
using Throw we can throw only one exception while for Throws we can declare multiple exceptions which
might occur in that particular function. Throws keyword followed by instance name and Throw keyword is
followed by class name of that exception.
• How much you rate yourself in selenium out of 5?
Out of 5 I will rate myself 3.5 in selenium.

• Which locator you are using in your framework and why?


Mostly we used ID and Xpath because Id is the fastest and unique one and after that we prefer Xpath.
Anyways we have other locators as well like css , class name, tag name, Link text, Partial Link text.

• What is the difference between findelement & findelements?


findelement will give the first appearance of that element which matches our locator, whereas
findelements will give us list of all the elements which is present over the webpage and matching our
locator. And if we don’t find the element findelement will give us nosuchelementexception whereas
findelements will return NULL/Empty list.

• Can you tell me how you will handle multiple window in selenium.
We have windowhandle & windowhandles function for handling Multiple windows. Windowhandle will
give the string value of only the active window that is open whereas windowhandles will give set of all the
windows that are open in browser.

• How you will move from one window to another?


First we will check what all windows are open by using driver.getwindowhandles, to get set of opened
windows , then I use iterator to iterate over each of the pages and inside for loop will check like Current
URL matches with the excepted page, if match then switch to that window by using
driver.switchTo(Destination window) -> to return back to main parent window use driver.defaultwindow.

• Tell me the difference between Implicit & Explicit wait?


Implicit wait applies for all the elements and all the tests like if we give 10 sec of implicit wait it will wait
for 10 sec for each element before giving nosuchelement exceptions.
While Explicit wait can be applied for any particular step for which you want extra wait time so we can use
explicit wait. We can use mix of both waits to depend on the situation of the step.

• Can you tell me some exceptions in selenium?


NoSuchElementException, NoSuchWindowException NoSuchframeException,
StaleElementReferenceException, TimeoutException.

• Can you tell me about StaleElementReferenceException?


Stale means old or decayed, here it sounds like element which was present on that page is no longer
there or decayed. To handle this, we can refresh the webpage before pointing to that element. We can
write script for waiting via explicit wait by writing expected condition.refresh. Or we can go with page
object model in that we can over come this stale element exception.

• What do you mean by User Defined Exception?


User Defined Exception or custom exception is creating your own exception class and throws
that exception using 'throw' keyword. This can be done by extending the class Exception. ... The keyword
“throw” is used to create a new Exception and throw it to the catch block.

• Can you tell me what is assert in TestNG?


Assert is like verification where we check like expected thing and actual thing are same or not.
• Which assert you have used in TestNg?
We have used Hard assert and Soft assert, while applying Hard assert if we found any glitch in expected
and actual then it will through exception and move to next @test while Soft assert it won’t give exception
and move to next step of that test. And to get all the exceptions in console we need to write at the end
assert.all.

• Can you tell me about the order of TestNG annotations?


@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite

• Do you heard about Priority in TestNg can we set -ve priority?


Yes, like priority is 0, -1, TestNg will run -1 then 0 then 1. And if we have any @test which is not having any
priority set, then in that case it will search via alphabetic order whichever comes first and execute test
respectively.

• Do you work in cucumber, can you tell me what all files required in cucumber?
In cucumber we have Feature file, Step Definition file and Test Runner file.
In feature file we used to write scenario in gherkin language which is most like in plain English language.
Here we use some of the keywords like feature, scenario, scenario outline, given, when, then, and,
example, background keywords for writing our test scenarios steps.
In Step Definition file we write mapping code for all the scenario of feature file.
In test Runner file we provide the address of the feature file, step definition file, and all-important Tags,
Plugin, Listeners in that.

• What is the difference between scenario & scenario outline?


When we have single scenario and we need to run it one time at that place we use Scenario.
If you want some parametrization or Data Driven testing at that time, we can use scenario outline where
we have to use Example keyword like if we are running this scenario for 3 different data set like username
& pass. so, it will run 3 times.

• Can you tell me more about Background Keyword?


Background is used when we have some common Given part. Suppose we have pre-condition that we
have to check this before each scenario. so in order to avoid rewriting same step we can write it in
Background.

• What is the use of Dry Run in cucumber?


Dry run is not running our whole application it will check whether all features are mapped with Step
definition.

• What is hooks in cucumber?


In cucumber we use hooks for common functionalities, hooks are like we want to run before & after each
of the scenario. In hooks we have 2 different @before, @ after which run before and after of each
scenario. Also @beforestep, @afterstep which run before and after each step.

• Can you tell me how you will re-run failed scenario in cucumber?
For that we can use re-run attribute in our test runner file. After that we can write one file location.
Where all the test cases which failed while execution get stored. So next time while running execution we
can give this file location and run the failed TC.

• You have worked in Cucumber & TestNG according to you which one is best?
I will consider Cucumber as it is most likely understood by Laymen people which is English plain language.
Because in order to understand the functionality flow no need to go look and script/code. Via Scenario
steps lines only we can get clear understanding about the functionality.
It helps to come all the QA members Dev, Client, Product Owner on same page.

• Can you explain me TestNG?


TestNG is advanced version of Junit only. It is mainly used by Dev/QA for maintain the code easily and for
unit testing. It provides lots of benefits to us like we can create a suite and we can write all the required Tc
in one go only using that suite. We can group our Tc we can set priority we can run our tc in parallel
mode, We can generate good reports via TestNG. We can write functionality depends on methods,
depends on group. We can run single tc multiple time with single set of data of multiple set of Data.

• How to run single method multiple time in TestNG?


We have invocation count attribute in @test annotiation. We can write invocation count as 3 if we want
to run it 3 times. Apart from that we can write threadpull.size if we want to run that case in multiple
thread.

• Have you used GIT in your project can you explain about it?
Yes I have used GIT, It is a version control tool. Where we can maintain our central repo. we used to
manage our code via GIT only. We use Git to maintain our project in our local system. So, if someone like
to work on that project I need to send complete update copy to him and after that he can work on that.
There are chances that single project is handled by multiple teams across the globe. So, it will be difficult
if we won’t use GIT.

• Can you give me some GIT commands which you used on daily basis?
Git status- which shows status of all the files,if we have some files which is not yet added to our repo so it
will give us untracked file.
After that we can use GIT add command after adding it will added to particular index and we can commit
this file using Git Commit-(Message) we can commit this untracked file. Also we have Git Merge, Git Post,
Git Pull, Git It in etc.

• How to solve Merge conflict in GIT?


As we are only 2 tester working on this project, if we have any merge conflict I used to pull all the latest
file/scripts to my local system. Then I will analyze the difference between that particular file and merge
file. After that I will check with my team member whether all his imp things are covered then I will add my
steps and push the script to the central repo.

• You have worked in Jenkins can you tell me how you have created jobs in Jenkins?
We have separate Dev-Ops Team to create Jenkins jobs at broad level but we also have access to jenkins,
so we have created jobs for our internal purpose.
For creating any job we have click on create new job->inside that give name of your job->select freestyle
project->then add. Beside that we can provide description of our project and in source code management
we can choose Git-> provide repo url ->after that provide some schedule if you want to run the job on any
specific schedule time.-> select window batch command-file location-save-click on build now for running.
After triggering we can check log in console.

• What is the difference between Smoke & Sanity Testing?


Smoke and Sanity we can are like same thing because both are checking important functionality.
Smoke testing is done on first stable build from developer to check like whether it is stable enough to
move further or not. While Sanity testing is subset of regression test which we perform on stable build
and here also we used to check all the imp functionality.

• What is Agile ceremony?


We have 4 Agile ceremony -Sprint planning, Sprint review, Sprint Retrospective, Daily scrum meeting.

• Why the main method is static?

Java main() method is always static, so that compiler can call it without the creation of an object or before
the creation of an object of the class. ... Static method of a class can be called by using the class name only
without creating an object of a class.

• What is Run time polymorphism

Run-Time Polymorphism: Whenever an object is bound with the functionality at run time, this is known
as runtime polymorphism. The runtime polymorphism can be achieved by method overriding. Java
virtual machine determines the proper method to call at the runtime, not at the compile time.

• Difference between list and set.

The main difference between List and Set is that Set is unordered and contains different elements,
whereas the list is ordered and can contain the same elements in it.

• Method overloading and overriding.

Method overriding is used to provide the specific implementation of the method that is already
provided by its super class. Method overloading is performed within class. Method overriding occurs in
two classes that have IS-A (inheritance) relationship. In case of method overloading, parameter must be
different.

• Use of constructor.

The purpose of constructor is to initialize the object of a class while the purpose of a method is to
perform a task by executing java code. Constructors cannot be abstract, final, static and synchronised
while methods can be. Constructors do not have return types while methods do.
• Difference between static and non-static methods

Static method uses complie time binding or early binding. Non-static method uses run time binding or
dynamic binding. A static method cannot be overridden being compile time binding. A non-static
method can be overridden being dynamic binding.

• Explain Git workflow.

Step 1: Set up a Github Organization. ...


Step 2: Fork Organization Repository to Your Personal GitHub. ...
Step 3: Clone the Repository to Your Local Machine. ...
Step 4: Create a Branch for your Working Files. ...
Step 5: Set Remote Repository to the GitHub Organization. ...
Step 6: Get Coding!
Step 7: Pull the Most Recent Files From the Organization Repo
Step 8: Merge the Master Branch Into the Feature Branch
Step 9: Push Your Code to your GitHub Repo
Step 10: Make a Pull Request to the Organization Repo

• How to set up Jenkins ?

Step 1 − Go to the Jenkins dashboard and Click on New Item

Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’

Step 3 − The following screen will come up in which you can specify the details of the job.

Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git
repository(E:\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the
URL of the local git repository.

Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click
on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from
the remote repository.

Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command

Step 6 − In the command window, enter the following commands and then click on the Save button.

Javac HelloWorld.java
Java HelloWorld

Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job.

Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress.

Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has
been executed successfully. Click on the #1 in the Build history to bring up the details of the build.

Step 10 − Click on the Console Output link to see the details of the build
• Can we declare many interfaces object class inside the interface class.

Yes, you can define a class inside an interface. In general, if the methods of the interface use
this class and if we are not using it anywhere else we will declare a class within an interface.

• Types of the assertion.

Selenium Assertions can be of three types: “assert”, “verify”, and ” waitFor”. When an “assert” fails, the
test is aborted. When a “verify” fails, the test will continue execution, logging the failure. A “waitFor”
command waits for some condition to become true.

• Abstraction in java and exp?


In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) in a Page Class. We
utilize these locators in tests but we can’t see these locators in the tests. Literally we hide the locators
from the tests.

• What is a super keyword in java?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to
access the superclass constructor. The most common use of the super keyword is to eliminate the
confusion between superclasses and subclasses that have methods with the same name.

• Difference between break and continue statement.

Break statement resumes the control of the program to the end of loop and made executional flow
outside that loop. Continue statement resumes the control of the program to the next iteration of that
loop enclosing 'continue' and made executional flow inside the loop again

• Diff between Abstract class & interface?

Abstract class can inherit another class using extends keyword and implement
an interface. Interface can inherit only an inteface. Abstract class can be inherited using extends
keyword. Interface can only be implemented using implements keyword.

• What is a static keyword in Java?

In the Java programming language, the keyword static indicates that the particular member belongs to a
type itself, rather than to an instance of that type. This means that only one instance of
that static member is created which is shared across all instances of the class.

• Have you used the action class and where it is used?

Using the Actions class in Selenium, we can implement the sendKeys() method to type specific values in
the application. That is how you use the actions class in Selenium with sendKeys() method. ... The
perform() method is used to perform the series of actions that are defined.

• What is the difference between checked and unchecked exceptions?


There are two types of exceptions: checked exception and unchecked exception. ... The main difference
between checked and unchecked exception is that the checked exceptions are checked at compile-time
while unchecked exceptions are checked at runtime

checked exceptions – SQLException,IOException,ClassNotFoundException,InvocationTargetException

unchecked exceptions –
NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException,IllegalArgumentException

NumberFormatException

• Apart from sendkeys, are there any different ways, to type content onto the editable field?

WebDriver driver = new FirefoxDriver();


JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.getElementById("textbox_id").value='new value';);

• What is static and non-static?

In non-static method, the method can access static data members and static methods as well as non-
static members and method of another class or same class. Binding process. Static method uses compile
time or early binding. Non-static method uses runtime or dynamic binding. Overriding.

• DIfference between this and super?

this keyword mainly represents the current instance of a class. On other hand super keyword represents
the current instance of a parent class. this keyword used to call default constructor of the same class.

• What is the difference between length and length() in Java?

The length is an instance variable of an array in Java whereas length() is a method of String class

• What is an abstract class?

Abstract Classes and Methods Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class). Abstract method: can only be used in an abstract
class, and it does not have a body. The body is provided by the subclass (inherited from).

• Difference between Actions and Action?

Actions is a class that is based on a builder design pattern. This is a user-facing API for emulating complex
user gestures. Whereas Action is an Interface which represents a single user-interaction action.

• How do you handle keystrokes in Selenium?

Using Actions Class: Actions action = new Actions(driver); action. keyDown(Keys. ...
Using SendKeys Chord: driver. findElement(By. ...
Using Robot Class: // Create Robot class Robot rb = new Robot(); // Press control keyboard key rb.
• What is dry run in Cucumber?

Dry-run is used to compile feature files and step definitions in cucumber. It is specially used in the stage
when you will have to see if there are any compilation errors, to check that you can use dry-run. Dry-
run options can either set as true or false.

• Annotations in Cucumber

Total 11 Annotations -Feature, Scenario, Background, given, when , then, and, but, example, scenario
outline, scenario template.

• What are hashmap and HashSet? Explain?

HashMap and HashSet both are one of the most important classes of Java Collection framework.
... HashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is
required for its retrieval during iteration. HashSet stores only objects no such key value pairs maintained.

• Where do you use a hashmap?

Maps are used for when you want to associate a key with a value and Lists are an ordered collection. Map is an
interface in the Java Collection Framework and a HashMap is one implementation of the Map
interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a
key. HashMap<String, Integer> map = new HashMap<>();

// Add elements to the map

map.put("vishal", 10);

map.put("sachin", 30);

map.put("vaibhav", 20);

// Print size and content

System.out.println("Size of map is:- "

+ map.size());

System.out.println(map);

// Check if a key is present and if

// present, print value

if (map.containsKey("vishal")) {

Integer a = map.get("vishal");

System.out.println("value for key"

+ " \"vishal\" is:- " + a);


• How do you handle if XPath is changing dynamically?

Option 1: Look for any other attribute which Is not changing every time In that div node like name, class
etc. So If this div node has class attribute then we can write xpath as bellow.

//div[@class='post-body entry-content']/div[1]/form[1]/input[1]

Option 2: We can use absolute xpath (full xpath) where you do not need to give any attribute names In
xpath.
/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div/div/div[1]/div/div/di
v/div[1]/div[2]/div[1]/form[1]/input[1]

Option 3: We can use starts-with function. In this xpath's ID attribute, "post-body-" part remains same
every time. //div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]

Option 4: We can use contains function. Same way you can use contains function as
bellow.div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]

• Does Jenkins require a local system for CI?

It is a server-based application and requires a web server like Apache Tomcat

• What is a singleton class?

The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since
there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just
like static fields. Singletons often control access to resources, such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble
with multithreading, the Singleton makes sure that only one connection is made or that only one thread
can access the connection at a time.

• When finally block get executed?

The finally block always executes when the try block exits. This ensures that the finally
block is executed even if an unexpected exception occurs.

• How many times you can write catch block?

maximum one catch block will be executed. No, we can write multiple catch block but only one is
executed at a time.

• What Maven Architecture and explain pom.xml?


POM is an acronym for Project Object Model. The pom. xml file contains information of project and
configuration information for the maven to build the project such as dependencies, build directory,
source directory, test source directory, plugin, goals etc. Maven reads the pom.

Real time selenium + Java interview questions.

• How many types of WebDriver API ’s are available in selenium?


Chrome, Geko, Chromium, Edge, html, android,
• How can you make sure that page is loaded via wed driver or selenium?
Via first apply wait , is element present, then get text.
• How can we launch a batch file in selenium webdriver project?
Take path of batch file->process.batchjob= runtime.get(runtime.executable”Path”));
• How do you run selenium webdriver test from the command line?
For that go to cmd-> java-class path(of the selenium project) ->hit enter
• What are the different exception you faced in selenium webdriver?
Webdriver exc, noalertpresent exc, nosuchwindow exc, nosuchelement exc, timeout exc.
• How do you scroll down a page using javascript in selenium?
Windows.scrollby function
• How do you scroll down to a particular element?
Windows.scroll.intoview function
• Which all files can be used as a data source for different frameworks?
.csv, .xml, .text etc
• What are listeners in selenium?
Listeners actually is an interface, that modifies the behavior of the system. It is used for customization of
reports. 2 types webdriver listeners, TestNg Listeners.
• How do you take screenshots in selenium webdriver?
takescreenshot function
• What do you mean by assertions in selenium?
Assert, verify, wait for
• How many phases are there in maven build cycle?
6 validate-compile-test-package-install-deploy
• How will you handle keyboard and mouse related action using selenium?
By action class, robot class, venium driver
• What do you mean by WebDriver?
Webdriver is an interface which is used to automate api of browser for testing.
• How do you handle drag and drop option? Using action classes
• How you handle java pop-ups in selenium? Using alert, switch to alert, accept, dismiss, get text.
• What does means Public static void main(variable,value)
Public/private/protected/default-Access specifier
Static- modifier
Void- return type
Main-class name
• How to input text into a text box without Sendkeys?
JavascriptExecuter executor = (JavascriptExecutor)driver;
executor.excuteScript(“document.getElementById(“<<inputbox_id>>”).value=’new value’);
• What are the open source frameworks supported by selenium webdriver?
TestNG, Junit, Cucumber, Robot Framework, Appium, Protractor.
• How to handle hidden elements in selenium webdriver?
JavascriptExecuter js = (JavascriptExecutor)driver;
js.excuteScript(“document.getElementById(“<<displayed_text>>”).value=’Hiddentext);

• How to handle iframes in selenium webdriver?


driver.switchTo().frames(via index value, name, webelement );
driver.findeElement(by.id(“value”)).getText();
driver.switchTo().defaultContent();-To get back from iframe

• How you handle dropdown values?


From select class, via visible text, value, index
• How to get color of webelement using selenium webdriver?
First get the locator of webElement , then get
String color= object.getCssValue(“background-color”)
String HexbackColor= color.fromString(color).asHex();
It will give you RGb codes , you need to convert them into back color using HEX function
• How you handle alert in selenium webdriver?
Simple alert(one option), Confirm Alert(Y/N), Prompt alert(enter any value)
Alert a= driver.switchTo().alert();
a.getText();
a.accept(), a.dismiss(), a.sendKeys(“name”);
• How you handle multiple windows tabs in selenium webdriver?
String PID=driver.getWindowHandle();
Set<String> allWindowHandle= driver.getWindowHandles();
Apply for loop on allWindowHandle -> switchTo().window(Id); ->if(!(Id.equals(PID)) ->driver.close();

JAVA ONE LINE CONCEPTS

• java file mai ek hi public class hoti hai, uske alava aur classes v ho sakti hai par public ek hi.
• If we need to create one variable for multiple values, we need to use Array concept.
• Int marks[] = new int[5]
• Array can store only homogenous data, int for int array, string for string,
• If we need to add heterogeneous data in array, we need to create object array.
• Object a[] = new Object[5]; now we can add different data type objects.
• Array is fixed in size, which we define while creating.
• If we try to access index value >= given index value, we got arrayOutOfBundException.
• Arrays are not defined by any data layer structure so we can’t run readymade methods on
it.
• To overcome this, we have collection framework under which there are ArrayList, List,
HashMap, HashTable, Tree, Stack.
• We can add new elements in run time under collections while in array we cannot.
• Collection is a group of objects. To represent this we need certain interfaces and classes.
• Common operations we generally do on collections are adding objects, removing objects &
finding object.
• Collection (I) is called collection interface having methods which are common throughout all
collections.
• Collections is basically a class from java.util package which contains some methods which
we can use for collection objects.
• Collection – 1. List, 2. Set, 3. Queue
• List (I) is child of collection(I). In list Insertion order is preserved and duplicates are allowed.
• ArrayList, LinkedList, Vector these are different classes which implements List Interface.
• Set(I) is child of collection(I). Insertion order is not preserved & duplicates not allowed.
• HashSet, Linked Hashset these are different classes which implements Set Interface.
• Queue(I) is child of collection(I). We used it when we need prior to processing means first in
first out concept.
• priorityQueue is class which implements Set Interface.
• There is one independent interface known as Map(I). In Map(I) objects are created with key
and value pair. Key cannot be duplicate, but Value can be.
• Hashmap, Linked Hashmap, Hash Table these are different classes which implements Map
Interface.
• Whatever methods present in Collection(I) are also present in their child interface i.e List,
Set, Queue.
• add(object o), addAll(Collection c), remove(Object o), removeAll(Collection c),
retainAll(Collection c) these are some methods of Collection Interface.
• clear(), isEmpty(), size(), contains(), conatinsAll(), toArray() are also some methods.
• In List index play an important role because with the help of index only we can find
duplicates elements.
• add(index , object), get(index), set(index, object) are methods of List Interface.
• ArrayList al= new ArrayList(), it allows heterogenous objects also.
• ArrayList<Str> al= new <str>(), now it can store objects of string only.
• Collections.Sort(al) , Collections.Shuffle(al) This will sort & shuffle the objects of arraylist.
• We can read the data with for loop, for each loop, iterator () method.
• JVM have 2 types of memories Static pool -static data, heaps-Non static data,

==================================================================================

OOPS ONE LINE CONCEPTS

• We can create multiple classes inside one main class.


• Class name cannot be a keyword.

• Object. with . we can access behavior and properties of that class or any other public class.
• In Polymorphism, we can create many methods with same name, differentiating with input
parameter. Void Walk(){}, void walk(int steps){} . We cannot create duplicate methods or one
method into another.
• Compile time polymorphism, tell which method is called before running it.
• By applying static it means now it became class property not object one and it applicable to all
objects throughout the class.
• Static methods are accessed by class, Non Static methods are accessed by objects.
• Constructor in java is to make objects, we can create constructor but there is one default
constructor in java, like students a = new students(); highlighted is the default constructor.
• Constructor are non static methods. Constructor can be parameterized
• We can create our own constructor like students b= new students(int rollNo ,String name){}
• this() keyword is used to call one constructor by another.
• this() keyword also used in agar 2 alag alag methods mai same parameter name hai , to conflict
na ho isliye this.name, this.rollNo use krte h. this is known as method overloading bcs you are
using one method parameter in second one.
• Inheritance ka matlab hai ki Parent class ki property ko hum child class mai bhi use kar sake.
• e.g class Sci extends students{}, extends keyword ki help se hum students class ki property
ko Sci class mai inherit kr rahe h.
• super() keyword parent class ke constructor ko child mai le ata hai , means ab agar hum Sci
class ka object baneyenge to students class ka v ek object banega.
• this() keyword call current class property, super() keyword call parent class property.
• Java ke andar jitne v by default objects hote hai unke ek parents class hoti hai object.
• Run time polymorphism tell which method is called while running it.
• Public method ka matlab hai hum us method ko ab jis class mai vo bna hai uske bhar bhi access
kr sakte hai uski class ka object bna ke.
• Aur isi point par Encapsulation ka concept v ata hai , hum kisi v method ko kisi v class mai
use kr sakte hai agar vo public hua , par agar hamne usko public na kar to ab vo method apni
class mai Encapsulate ho gya ab usko koi aur use nahi kar skta, ise hi Encapsulation bolte
hai.
• Public, private, protected inko access modifier bolte hai.
• Agar hamne kisi method ko Private bnaya hai to vo bas usi class mai hi use ho skta hai aur
kahi nahi.
• Agar hum chate hai ki parent class ki property bas uske child class ko mile to un
properties/methods ko hum Protected kar dete hai.
• Encapsulation isliye v karte hai bcs hame same kind of variables and method jo kisi ek kam
ke liye specially bne ho unko ek sath le aye. Is se data hiding mai help milti hai and security v
increase hoti hai.
• Aur yahi par getter and setter ka funda ata hai.
• Abstraction iska matlba hai ki hum unnecessary info ko user se hide kre taki usko main
functionality par focus rahe na k internal logic pr.
• e.g ATM withdraw, user ko bas apna pin no cahiye aur kitna paise nikalana hai , uske piche
kya kya process hota hai uska use koi lene dene nahi hai. To jis process ka user ko kuch lena
dena nahi use background mai rakhna ise Abstraction kehte h.
• abstract keyword agar kisi class ke sath lagaya hai to hum uska objects nahi bna sakte.
• Ha bas abstract class ko extend kake hum uske children class mai objects bna skate hai
only override karke.
• Aur agar hum kisi class ko abstract banate hai to hame usme kuch logic dene ki jaroort nahi
hai. Aur ye ek imp property hai abstract method ki.
• Abstract method bannna hai to uski class ko bhi abstract bannna padega.
• Interface methods are by default public and abstract.
• Abstract method ke andar hum concrete functions bna sakte hai , par interface ke andar
kuch nahi bna sakte.
• Interface hame complete Abstraction provide karata hai.
• Interface ko use karne ke liye hum implements keyword use karte h.
• Class-extends-class, class-implements-interface, interface-extends-interface
• Java mai ek class ke multiple parent nahi ho sakte bcs java multiple inheritance support ni
krta. Iske liye hum interface ka use karte hai.
• Tokens in java, Token is known as the smallest unit of your program, the whole java code
you have written is a token.
• Literals means are the string values, integer values, comments, keyword.
COLLECTION FRAMEWORK

• A collection represents a group of objects.


• Java collections provide classes and Interfaces for us to be able to write code.
• We need collections for efficient storage and better manipulation of data in java.
• Collection reduces programming effort, provide in-build methods and classes.
• ArrayList -> For variables size collections
• Set -> For distinct collection
• Stack(queue)-> A LIFO (Last In First Out) data structure
• HashMap -> For strong key - value pairs
• Iterator- To iterate the element from collection.
• Collections class is available in java util package collection class also provides static methods for
sorting, searching.
• Common methods available in Collection are add(), addAll(), remove(), removeAll(), size(),
clear(), contains(), containsAll(), retain(), retainAll()
• Common exception is collections are NullPointerException, ClassCastException,
IllegalargumentException, IllegalStateException, UnsupportedOperationException


• Thread Safety-When multiple threads are working on same data, and the value of our data is
changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is
already working on an object and prevent another thread on working on the same object is
known as thread safety. We can achieve Thread safety via Synchronization, Volatile Keyword,
Atomic variable, Final Keyword.

Array List:
• ArrayList<Object Type> ar = new ArrayList<Object Type>();
• ArrayList is Dynamic in nature.
• Virtual Capacity of ArrayList by default is 10 but Physical capacity if we did not add any object is
0. Once we start adding Physical objects Virtual Capacity got decreased by same.

Hashmap:

• Hashmap<String, String>capitalmap = new Hashmap<String, String>();


capitalmap.put(“India”, “New Delhi”);

Java HashMap Interview Questions:

1.How does put() method of HashMap works in Java?

On hashing principle of key value pair


2. What is the requirement for an object to be used as key or value in HashMap?
3. What will happen if you try to store a key which is already present in HashMap?
4. Can you store a null key in Java HashMap?
5. Can you store a null value inside HashMap in Java?
6. How does HashMap handle collisions in Java?
7. Which data structure HashMap represents?
8. Which data structure is used to implement HashMap in Java?
9. Can you store a duplicate key in HashMap? (answer)
10. Can you store the duplicate value in Java HashMap? (answer)
11. Is HashMap thread-safe in Java?
12. What will happen if you use HashMap in a multithreaded Java application?
13. What are the different ways to iterate over HashMap in Java?
14. How do you remove a mapping while iterating over HashMap in Java?
15. In which order mappings are stored in HashMap?
16. Can you sort HashMap in Java? (answer)
17. What is the load factor in HashMap? A load factor is a number that controls the resizing
of HashMap when a number of elements in the HashMap cross the load factor as if the load
factor is 0.75 and when becoming more than 75% full then resizing trigger which involves
array copy.
18. How does resizing happens in HashMap? (answer)
19. How many entries you can store in HashMap? What is the maximum limit?
20. What is the difference between the capacity and size of HashMap in Java?
21. What will happen if two different keys of HashMap return the same hashcode()?

==================================================================================

String one line que.

java.lang.String class is used to create a string object.


Different String methods:

• compareTo - The Java String compareTo() method is used for comparing two strings
lexicographically.
• boolean equals() - The java string equals() method compares the two given strings
based on the content of the string (case sensitive)
• String concat() – concat two strings
• boolean equalsIgnoreCase() - The java string equals() method compares the two given
strings based on the content of the string (not casesensitive)
• char charAt() – index position - The java string charAt() method returns a char value at
the given index number.
• boolean contains()
• toUpperCase() – convert to upper case
• toLowerCase() – convert to lower case
• trim() – remove spaces from both sides of string
• substring() -- returns part of string
• boolean endsWith()
• boolean startWith() – ends with specified suffix or not
• int length()
• replace()
• int num = Integer.parseInt(str);- Convert String to int using Integer.parseInt(String)
• int num = Integer.valueOf(str);- Convert String to int using Integer.valueOf(String)
• Convert int to String using String.valueOf()
String int ivar = 123;
String str = String.valueOf(ivar);
System.out.println("String is: "+str);
System.out.println(555+str);
• Convert int to String using Integer.toString()
int ivar = 123;
String str = Integer.toString(ivar);
System.out.println("String is: "+str);
System.out.println(555+str);
• In java, string objects are immutable. Immutable simply means unmodified or
unchangeable.Once string object is created its data or state can't be changed but a new
string object is created.
==================================================================================
Array one line que.

• Write down syntax of iterator function?


Iterator<String> it = studentList.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

• How to find max min of an unsorted array?


MAX
public class maxmin {
public static void main(String[] args) {
int [] arr = {1, 45, 67, 98, 455, 678};
int max = Integer.MIN_VALUE;
for ( int element : arr){
if(element>max){
max=element;
}
}
System.out.println(“Max element is " + max);
}}
MIN
public class maxmin {
public static void main(String[] args) {
int [] arr = {1, 45, 67, 98, 455, 678,-6};
int min = Integer.MAX_VALUE;
for ( int element : arr){
if(element<min){
min=element;
}
}
System.out.println(“Min element is " + min);
}}
=============================================================================
• How to reverse any array?
public class reverse array {
public static void main(String[] args) {
int [] arr = {1, 45, 67, 98, 455, 678};
int l = arr.length;
int n = Math.floorDiv(l,2);
int temp;
for(int i=0; i<n;i++){
temp= arr[i];
arr[i]= arr[l-i-1];
arr[l-i-1]= temp;
}
for(int element:arr)
{
System.out.print( element + " ");
}
}}
================================================================
public class reverse array {
public static void main(String[] args) {
int [] Array ={7,8,9,3,4,6,11,67,98};
int k=Array.length-1;
for(k=Array.length-1;k>=0;k--){
System.out.print( Array[k] + " ");
}
}}
=====================================================================

• How to remove duplicate elements from ArrayList?


we can handle this scenario via LikedHashSet
ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList(1,2,2,4,6,7,2,3,5,4,3,8,2,8));
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(numbers);
ArrayList<Integer> numbersListWithoutDuplicate = new ArrayList<Integer>(LinkedHashSet));
System.out.println(numbersListWithoutDuplicate);

Also we can handle this via stream


ArrayList<Integer> marksList = new ArrayList<Integer>(Arrays.asList(1,2,2,4,6,7,2,3,5,4,3,8,2,8));
List<Integer> marksListUnique= marksList.stream().distnict().collect(Collectors.toList());
System.out.println(marksListUnique);

• How to compare two array list?


Via Collection.sort(); and equal

• How to find additional element in list while comparing 2 List?


If we have 2 list l1 & l2 , first we remove all element of l2
L1.removeAll(l2):
Sysout(L1) – you will get additional element.

• How to find common element in list while comparing 2 List?


L1.retainAll(L2);
Sysout(L1) – you will get common element.

• How will you print length of string without using length method.
String str = “Pankaj”
Sysout(str.toCharArray().length);
Sysout(str.lastIndexOf(“”));

• How to find missing element in integer array?

• How to reverse a string?


1.
String str = “Pankaj”;
int len = str.length();
String rev = ” ”
for(int i<len-1 , i>=0, i--){
rev = rev + str.charAt(i);
}
Sysout(rev);

2.
Create a string-> create new stringBuffer and here you can apply reverse fuction.
String str = “Pankaj”;
StringBuffer sf = new StringBuffer(s);
Sysout(sf.reverse());

• How will you remove special/junk char from string?


We have to use regular expression [a-z, 0-9, A-Z]

String str = “Y^%^*%&*^*(&*(Pankaj”;


Str= Str.replaceAll([^a-z, 0-9, A-Z], “”);
Sysout(str);

• How to reverse an Integer?

int num = 12345;


int rev = 0;
while(num !=0){
rev =rev *10+ num % 10;
num = num/10;
}
Sysout (rev)
}

• How to find duplicate char using hashmap?


• Find the count of char using hashmap?
• Top 7 Selenium Commands with Details
• #1) get() Methods
• driver.get("https://google.com");

• driver.getClass();

• driver.getCurrentUrl();

• driver.getPageSource();

• driver.getTitle();

• driver.getText();
• driver.findElement(By.id("findID")).
getAttribute("value");

• driver.getWindowHandle();


• #2) Locating links by linkText() and partialLinkText()
• driver.findElement(By.linkText(“Google”)).click();

driver.findElement(By.partialLinkText(“abode”)).click();

• #3) Selecting multiple items in a drop dropdown
• // select the multiple values from a dropdown
• Select selectByValue = new Select(driver.findElement(By.id("SelectID_One")));
• selectByValue.selectByValue("greenvalue"); - By Value
• selectByValue.selectByVisibleText("Red"); - By Visible Text
• selectByValue.selectByIndex(2); - By Index
• #4) Submitting a form
• // submit the form
• driver.findElement(By.<em>id</em>("submit")).submit();
• #5) Handling iframes
• Select iframe by id
driver.switchTo().frame(“ID of the frame“);

• Locating iframe using tagName
• driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));

• Locating iframe using the index:
• a) frame(index)
driver.switchTo().frame(0);
• b) frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
• c) frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();

• #6) close() and quit() methods
• driver.close(); - closes only a single window that is being accessed by the WebDriver instance
currently

• driver.quit();- closes all the windows that were opened by the WebDriver instance

• #7) Exception Handling
• WebElement saveButton = driver.findElement(By.id("Save"));
• try{
• if(saveButton.isDisplayed()){
• saveButton.click();
• }
• }
• catch(NoSuchElementException e){
• e.printStackTrace();
• }
• #4) isEnabled()

• isEnabled() to Check Whether the Element is Enabled Or Disabled in the Selenium WebDriver.

• findElement(By, by) with sendKeys() to type in the form fields.

• findElement(By, by) with getText() to store value of targeted web element.

• Submit() to submit a web form.

• findElements(By, by) to get the list of web elements.
• List<WebElement> allChoices = dropDown.findElements(By.xpath(".//fruitoption"));
• findElements(By, by) with size() to verify if an element is present.
• Boolean checkIfElementPresent=
driver.findElements(By.xpath("//input[@id='checkbox2']")).size()!= 0;
• pageLoadTimeout(time,unit) to set the time for a page to load
• driver.manage().timeouts().pageLoadTimeout(500, SECONDS);
• implicitlyWait() to set a wait time before searching and locating a web element.
• driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);
• untill() from WebdriverWait and visibilityOfElementLocated() from ExpectedConditions to
wait explicitly till an element is visible in the webpage.
• WebDriverWait wait = new WebDriverWait(driver, 10);
• WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//input[@id=’name’]")));
• untill() from WebdriverWait and alertIsPresent() from ExpectedConditions to wait explicitly
till an alert appears.

• WebDriverWait wait = new WebDriverWait(driver, 10);
• WebElement element = wait.until(ExpectedConditions.alertIsPresent()
• );
• Select class for selecting and deselecting values from the drop-down in Selenium
WebDriver.
• WebElement mySelectedElement = driver.findElement(By.id("select"));
• Select dropdown= new Select(mySelectedElement);dropdown.selectByVisibleText("Apple");
• navigate() to navigate between the URLs.
• driver.navigate().to("https://www.softwaretestinghelp.com");
• driver.navigate().back();
• driver.navigate().forward();
• getScreenshotAs() to Capture the entire page screenshot in Selenium WebDriver.
• File shot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
• FileUtils.copyFile(shot, new File("D:\\ shot1.jpg"));
• moveToElement() from the Actions class to simulate mouse hover effect.
• Actions actions = new Actions(driver);
• WebElement mouseHover = driver.findElement(By.xpath("//div[@id='mainmenu1']/div"));
• actions.moveToElement(mouseHover);
• actions.perform();
• dragAndDrop() from Actions class to drag an element and drop it on another element.

• WebElement sourceLocator = driver.findElement(By.xpath("//*[@id='image1']/a"));
• WebElement destinationLocator = driver.findElement(By.xpath("//*[@id='stage']/li"));
• Actions actions=new Actions(driver);
• actions.dragAndDrop(sourceLocator, destinationLocator).build().perform();
• switchTo() and accept(), dismiss() and sendKeys() methods from Alert class to switch to
popup alerts and handle them.

• Alert alert = driver.switchTo().alert();
• alert.sendKeys("This Is Softwaretestinghelp");
• alert.accept()
• getWindowHandle() and getWindowHandles() to handle Multiple Windows in Selenium
WebDriver.

• String handle= driver.getWindowHandle();
• Set<String> handle= driver.getWindowHandles();
• for (String handle : driver.getWindowHandles()){
• driver.switchTo().window(handle);
• }
• getConnection() from DriverManager to start Database Connection.
• DriverManager.getConnection(URL, "username", "password" )
• POI to read from the excel files.
• Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
• Sheet sheet = workbook.getSheetAt(0);
• Asserts using assertEquals(),assertNotEquals(), assertTrue() and assertFalse() to compare
the results.
• Assert.assertEquals(message, “This text”);
• Assert.assertNotEquals(message, “This text”);
• Assert.assertTrue(result<0);
• Assert.assertFalse(result<0);
Selenium Notes

1. What is Selenium ?

Selenium is an open source web automa on tool.

Limitation of Selenium :

● It doesn’t support windows based applica on directly. However, third party tool (eg: AutoIt) can be
integrated with selenium to automate windows based applica ons.

Note :

1. Selenium community developed specific tool called WINIUM to automate windows based applica ons.
2. Selenium community also developed tools to test mobile applica ons,
● Selendroid - it supports only Android pla orm
● Appium - it supports Android pla orm, MAC, Windows etc.

Note :

All the selenium related resources and documents can be found on the below website.

h p://www.seleniumhq.org

Here, hq stands for head quarter.

-------------------------------------------------------------------------------------------------------

2. Why Selenium is so popular and demanding ?

Selenium is popular and demanding due to the following features.

1. it is an open source tool freely available on internet


2. No project cost involved
3. No licence required
4. Can be easily customized to integrate with other Test Management tools like ALM, Bugzilla etc.
5. It supports almost 13 different so ware languages
● Java
● C#
● Ruby
● Python
● Perl
● Php
● Javascript
● Javascript (Node JS)
● Haskell
● R
● Dart
● TCL
● Objec ve - C
6. It supports almost all the browsers.(Firefox, Chrome, Internet Explorer etc) and

hence, cross browser tes ng/compa bility tes ng can be performed using selenium.

7. It supports almost all the Opera ng System (MAC, Windows, LINUX etc) and hence,

cross pla orm tes ng can also be performed.

--------------------------------------------------------------------------------------------------------

3. What are the different flavours of Selenium ?

● Selenium Core (Developed by a company called Thought Works way back in 2004)
● Selenium IDE (supports only Mozilla Firefox - supports record and playback feature)
● Selenium RC (Remote Control - Version is 1.x) (Used for parallel execu on of automa on scripts on
mul ple remote systems)
● Selenium WebDriver (Version is 2.x and 3.x)

Note :

Selenium WebDriver version 3.x is no longer capable of running Selenium RC directly, rather it does through
emula on and via an interface called WebDriverBackedSelenium.

But, it does support Selenium Grid directly.

Selenium Grid :

1. It is one of the component of selenium that is used to run automa on scripts on mul ple system
simultaneously.
2. It is used to carry out compa bility tes ng on mul ple browsers and pla orms.

--------------------------------------------------------------------------------------------------------

4. What are the key/Important topics of Selenium ?

● Automation Framework - guidelines and rules to write selenium code


● GitHub - Central Repository to store code
● Maven - build dependency tool for auto update of selenium version
● Selenium Grid - to test on mul ple OS and browsers
● Jenkins - Con nuous Integra on
● TestNG - framework for genera on of Test Reports and running mul ple test scripts in one go

--------------------------------------------------------------------------------------------------------

5. What are the Softwares required for Selenium ?


1. Eclipse IDE - Oxygen (Stable version)
2. JDK 1.8
3. Selenium Server-Standalone-3.7.1 (Stable version)

(Download it from the given url : http://www.seleniumhq.org/download)

4. Driver Executables

❖ For Firefox Browser


➢ the name of the driver executable is : geckodriver.exe
➢ Url to download : h ps://github.com/mozilla/geckodriver/releases
➢ Version 0.19 is recommended for firefox browser with version 56.0 (selenium jar - 3.7.1)
❖ For Chrome browser
➢ the name of the driver executable is : chromedriver.exe
➢ Url to download : h ps://chromedriver.storage.googleapis.com/index.html?path=2.31/
➢ Stable version of chrome version is 62.0 (Use chromedriver.exe with version 2.33)

5. Browsers:

Firefox (Version 57.0)

Chrome (Version 62.0)

Note : To stop auto update of firefox browser version, Make sure to disconnect the internet connec on
and then install 54.0 version, now go to Se ng/Op on in firefox browser and check the below checkbox -
Never check for updates.

6. Application Under Test (AUT)

Application Name : ac TIME

Online url : https://demo.actitime.com/login.do

Offline url : https://localhost:8080/login.do


To download actiTIME application ,

https://www.actitime.com/download.php

--------------------------------------------------------------------------------------------------------

6. Selenium Architecture - High Level ?

OR

How selenium performs automation testing on browser ?

Client Binding Driver Executables Browser

OR .jar file uses

Language Binding JSON Wire Protocol

1. Since selenium supports multiple languages such as Java, Python, C# etc, we can develop automation
scripts in all the supported languages. This is know as language binding or Client binding.
2. When we execute the selenium code, request goes to the Selenium Standalone Server (also known as
Selenium WebDriver Server), which further process the request based on the input received from the
client binding and perform specific actions on the respective browsers using the browser specific driver
executables,

Eg : geckodriver.exe for firefox browser and

chromedriver.exe for chrome browser and so on…

3. Driver executables uses a protocol called JSON Wire protocol to communicate with related

browsers. (JSON stands for Java Script Object Notation)

--------------------------------------------------------------------------------------------------------

7. Selenium Java Architecture - Detailed Level


1. SearchContext is the supermost interface present in selenium webdriver.
2. An interface called WebDriver extends SearchContext interface.
3. A total of 13 interfaces are available in selenium, which is implemented by a super most class called
RemoteWebDriver
4. RemoteWebDriver is again extended by few browser specific child classes such as,
● FirefoxDriver class to automate on firefox browser.
● ChromeDriver class to automate on Chrome browser,
● InternetExplorerDriver class to automate on IE and so on…….

NOTE :

All the above men oned interfaces and classes are present in a package called “org.openqa.selenium”.

To view any information about Selenium interfaces, classes and methods, navigate to the below page.

https://github.com/SeleniumHQ/selenium/tree/master/java/client/src/org/openqa/selenium

Highlighted below in red is the navigation path.


-------------------------------------------------------------------------------------------

8. List down all the methods present in below interfaces of Selenium WebDriver.

Methods of SearchContext interface :

1. findElement()
2. findElements()

Methods of WebDriver interface :

1. close()
2. get()
3. getTitle()
4. getPageSource()
5. getCurrentUrl()
6. getWindowHandle()
7. getWindowHandles()
8. manage()
9. navigate()
10. quit()
11. switchTo()

Methods of TakesScreenshot interface :


1. getScreenshotAs(args)

Methods of JavascriptExecutor interface :

1. executeScript()
2. executeAsyncScript() - we don’t use this for automation

Methods of WebElement interface :

1. clear()
2. click()
3. getAttribute()
4. getCssValue()
5. getLocation()
6. getRect()
7. getSize()
8. getTagName()
9. getText()
10. isDisplayed()
11. isEnabled()
12. isSelected()
13. sendKeys()
14. submit()

9. Why we upcast the browser related child class to WebDriver, and not RemoteWebDriver class
(RemoteWebDriver being the super most class in selenium) ?

Upcasting Example :

WebDriver driver = new FirefoxDriver();

● Conver ng a child class object to super type is called Upcas ng.


● In selenium, we use upcas ng so that we can execute the same script on any browser.
● In selenium, we can upcast browser object to RemoteWebDriver, WebDriver, TakesScreenshot ,
JavascriptExecutor etc, but a standard prac ce is to upcast to WebDriver interface.
● This is as per the Selenium coding standard set by the Selenium community. As a tes monial, navigate to
the below selenium community site and check for the text as men oned in the image below.

Url - h p://www.seleniumhq.org/projects/webdriver/
-------------------------------------------------------------------------------------------

10. Where did you use Upcasting in Selenium ?

WebDriver driver = new FirefoxDriver();

Explain the above statement..

1. WebDriver is an interface in Selenium that extends the supermost interface called SearchContext.
2. driver is the upcasted object or WebDriver interface reference variable.
3. “ = ” is an assignment operator.
4. new is a keyword using which object of the FirefoxDriver class is created.
5. FirefoxDriver() is the constructor of FirefoxDriver class which ini alises the object and it will also launch
the firefox browser.

-------------------------------------------------------------------------------------------

11. Steps to install/integrate selenium server to the java project

1. Launch eclipse and go to package explorer [naviga on path :- Window menu → Show View → Package
Explorer]
2. Create a java project [File → New→ Java Project]
3. Right click on Java Project and add a new folder with name “driver” [File → New→ Folder]
4. copy geckodriver.exe file from your system and paste it into this driver folder
5. Similarly, create another folder with name “jar”and copy Selenium Standalone Server.jar file into this jar
folder.
6. Expand the jar folder and right click on Selenium Standalone Server.jar file → select Build Path → select
Add to Build Path
7. As soon as you add any .jar files to build path, a new folder will be available called “Reference Libraries”
under the package explorer sec on and you can see the .jar file is added to this “Reference Libraries”
8. To remove the .jar file from the java build path, go to the Reference Libraries → select the .jar file → right
click → select build path → Remove from build path.
9. Other way of adding .jar file to java build path is : right click on the project → build path → configure build
path → Libraries tab → Add External jars → select the .jar file → Apply → ok

12. This program demonstrates Upcasting concept (FirefoxDriver class object to WebDriver interface) and
accessing various methods of WebDriver interface
package qspiders;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

public class UpcastingToWebDriver_LaunchBrowser {

public static void main(String[] args) throws InterruptedException {

//setting the path of the gecko driver executable

System.setProperty("webdriver.gecko.driver", ".\\driver\\geckodriver.exe");

//Launch the firefox browser

WebDriver driver = new FirefoxDriver();

//Enter the url

driver.get("http://www.google.com");

//Get the title of the google page and print it on the console

String title = driver.getTitle();

System.out.println("the title of the page is :"+ title);

//Get the URL of the google page and print it on the console

String currentUrl = driver.getCurrentUrl();

System.out.println("the URL of the page is :"+ currentUrl);

//Get the source code of the google page and print it on the console

String pageSource = driver.getPageSource();

System.out.println("the source code of the page is :"+ pageSource);

//Halt the program execution for 2 seconds

Thread.sleep(2000);

// Close the browser

driver.close();

}
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

1 What is SDLC?

SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.

2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead

3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User

4 What are Popular SDLC models?


Waterfall model: Waterfall model works well for smaller projects where requirements are very
well understood. The waterfall is a widely accepted SDLC model. In this approach, the whole
process of the software development is divided into various phases. In this SDLC model, the
outcome of one phase acts as the input for the next phase.
Incremental Model: The incremental model is not a separate model. It is essentially a series of
waterfall cycles. The requirements are divided into groups at the start of the project. For each
group, the SDLC model is followed to develop software. The SDLC process is repeated, with
each release adding more functionality until all requirements are met. In this method, every
cycle act as the maintenance phase for the previous software release. Modification to the
incremental model allows development cycles to overlap. After that subsequent cycle may
begin before the previous cycle is complete.
V-Model: In this type of SDLC model testing and the development, the phase is planned in
parallel. So, there are verification phases on the side and the validation phase on the other side.
V-Model joins by Coding phase.
Agile Model: Agile methodology is a practice which promotes continue interaction of
development and testing during the SDLC process of any project. In the Agile method, the
entire project is divided into small incremental builds. All of these builds are provided in
iterations, and each iteration lasts from one to three weeks. In ‘Agile Model’ after every sprint
there is a demoable feature to the customer. Hence customer can see the features whether
they are satisfying their need or not. Each release is thoroughly tested to ensure software
quality is maintained. It is used for time critical applications.

Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.

5 What is Software Testing?


According to ANSI/IEEE 1059 standard – A process of analyzing a software item to detect
the differences between existing and required conditions (i.e., defects) and to evaluate the
features of the software item.

6 What are the principles of software testing?


6.1 Testing shows presence of defects
Software Testing reduces the probability of undiscovered defects remaining in the
software but even if no defects are found, it is not a proof of correctness.
6.2 Exhaustive testing is impossible
If you were testing this Operating system, you would realize that defects are likely to be
found in multi-tasking activity and need to be tested thoroughly which brings us to our
next principal Defect Clustering.
6.3 Early testing
Early Testing - Testing should start as early as possible in the Software Development Life
Cycle. So that any defects in the requirements or design phase are captured in early
stages.
6.4 Defect clustering
Defect Clustering which states that a small number of modules contain most of the
defects detected. If the same tests are repeated over and over again, eventually the
same test cases will no longer find new bugs.
6.5 Pesticide Paradox
Repetitive use of the same pesticide mixes to eradicate insects during farming will over
time led to the insect’s developing resistance to the pesticide Thereby ineffective of
pesticides on insects. The same applies to software testing. If the same set of repetitive
tests are conducted, the method will be useless for discovering new defects. To
overcome this, the test cases need to be regularly reviewed & revised, adding new &
different test cases to help find more defects.
6.6 Testing is context depending
Testing is context dependent which basically means that the way you test an ecommerce site
will be different from the way you test a commercial off the shelf
application. All the developed software’s are not identical. You might use a different
approach, methodologies, techniques, and types of testing depending upon the
application type.
6.7 Absence of error - Fallacy
It is possible that software which is 99% bug-free is still unusable. This can be the case if
the system is tested thoroughly for the wrong requirement. The absence of Error is a
Fallacy i.e. Finding and fixing defects does not help if the system build is unusable and
does not fulfill the user's needs & requirements.

7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.

Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.

9 What are the Quality assurance and Quality Control standards?


Quality assurance system standards, including ISO 9001, are defined as frameworks that
provide regulations to organizations to ensure that their processes, inputs, products, and
services are capable of meeting every customer requirement.
• Ensuring maximum satisfaction of clients by meeting their quality requirements
• Safety of products and services during usage
• Complying with international regulations and local legislative rules
• Being environmentally responsible
• Confidentiality of stakeholders including customers, employees, partners, and investors
• Assuring a safer workplace for employees
• Optimum allocation of resources and minimization of waste

10 What is Verification & Validation in software testing?


• Validation: Are we building the right system?
• Verification: Are we building the system, right?

In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.

11 What is Test Plan Document?


Test plan document is a document which contains the plan for all the testing activities to be
done to deliver a quality product. Test Plan document is derived from the Product
Description, SRS, or Use Case documents for all future activities of the project. It is usually
prepared by the Test Lead or Test Manager.
1. Test plan identifier
2. References
3. Introduction
4. Test items (functions)
5. Software risk issues
6. Features to be tested
7. Features not to be tested
8. Approach
9. Items pass/fail criteria
10. Suspension criteria and resolution requirements
11. Test deliverables
12. Remaining test tasks
13. Environmental needs
14. Staff and training needs
15. Responsibility
16. Schedule
17. Plan risks and contingencies
18. Approvals
19. Glossaries

12 What is Test Strategy?


Test Strategy is a high-level document (static document) and usually developed by project
manager. It is a document which captures the approach on how we go about testing the
product and achieve the goals. It is normally derived from the Business Requirement
Specification (BRS). Documents like Test strategy doc is project-based document it can
change according to project domain and requirements.

13 What is Test Suite?


Test Suite is a collection of test cases. The test cases which are intended to test an
application.

14 What is Test Scenario?


Test Scenario gives the idea of what we have to test. Test Scenario is like a high-level test
case.

15 What is Test Case?


Test cases are the set of positive and negative executable steps of a test scenario which has
a set of pre-conditions, test data, expected result, post-conditions and actual results.

16 What is Test Bed?


An environment configured for testing. Test bed consists of hardware, software, network
configuration, an application under test, other related software.

17 What is Test Environment?


Test Environment is the combination of hardware and software on which Test Team
performs testing. Example:
• Application Type: Web Application
• OS: Windows
• Web Server: IIS
• Web Page Design: Dot Net
• Client-Side Validation: JavaScript
• Server-Side Scripting: ASP Dot Net
• Database: MS SQL Server
• Browser: IE/Firefox/Chrome

18 What is Test Data?


Test data is the data that is used by the testers to run the test cases. Whilst running the test
cases, testers need to enter some input data. To do so, testers prepare test data. It can be
prepared manually and also by using tools.

19 What is Test Harness?


Test Harness in Software Testing is a collection of stubs, drivers and other supporting tools
required to automate test execution. Test harness executes tests by using a test library and
generates test reports. Test harness contains all the information needed to compile and run
a test like test cases, target deployment port (TDP), source file under test, stubs, etc.
20 What is Test Closure?
Test Closure is the note prepared before test team formally completes the testing process.
This note contains the total no. of test cases, total no. of test cases executed, total no. of
defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected
etc.,

21 What is Risk Factor and its Types?


In software testing Risks are the possible problems that might endanger the objectives of
the project stakeholders. It is the possibility of a negative or undesirable outcome. A risk is
something that has not happened yet and it may never happen; it is a potential problem.
The types of Risk in a Test Project can be broadly categorized as
1. Strategy Risk: This includes Budget, Communication and Management risks
2. Project Definition Risks: This includes Project target, Scope, and requirements risks.
3. Human Resources Risk: This includes Skill, Team members and organization risks.

22 What are the tasks of Test Closure activities in Software Testing?


Test Closure activities fall into four major groups.
Test Completion Check: To ensure all tests should be either run or deliberately skipped
and all known defects should be either fixed, deferred for a future release or accepted as a
permanent restriction.
Test Artifacts handover: Tests and test environments should be handed over to those
responsible for maintenance testing. Known defects accepted or deferred should be
documented and communicated to those who will use and support the use of the system.
Lessons learned: Analyzing lessons learned to determine changes needed for future
releases and projects. In retrospective meetings, plans are established to ensure that good
practices can be repeated and poor practices are not repeated.
Result: Archiving results, logs, reports, and other documents and work products in the
CMS (configuration management system).

23 List out Test Deliverables?


1. Test Strategy
2. Test Plan
3. Effort Estimation Report
4. Test Scenarios
5. Test Cases/Scripts
6. Test Data
7. Requirement Traceability Matrix (RTM)
8. Defect Report/Bug Report
9. Test Execution Report
10. Graphs and Metrics
11. Test summary report
12. Test incident report
13. Test closure report
14. Release Note
15. Installation/configuration guide
16. User guide
17. Test status report
18. Weekly status report (Project manager to client)

24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status

25 Types of Traceability Test Matrix


In Software Engineering, traceability matrix can be divided into three major components as
mentioned below:
• Forward traceability: This matrix is used to check whether the project progresses in the
• forward desired direction and for the right product. It maps requirements to test cases.
• Backward or reverse traceability: It is used to ensure whether the current product
• remains on the right track. It maps test cases to requirements.
• Bi-directional traceability (Forward + Backward): This traceability matrix ensures that all
• requirements are covered by test cases. It analyzes the impact of a change in
• requirements affected by the Defect in a work product and vice versa.

26 How to create Requirement Traceability Matrix?


On the basis of the Business Requirement Document (BRD) and Technical Requirement
Document (TRD), testers start writing test cases.
Step 1: Our sample Test Case is
"Verify Login, when correct ID and Password is entered, it should log in successfully"
Step 2: Identify the Technical Requirement that this test case is verifying. For our test case, the
technical requirement is T94 is being verified.
Step 3: Note this Technical Requirement (T94) in the Test Case.
Step 4: Identify the Business Requirement for which this TR (Technical Requirement-T94) is
defined
Step 5: Note the BR (Business Requirement) in Test Case
Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your Test Suite. RTM
in testing is Ready!

27 Advantage of Requirement Traceability Matrix


• It confirms 100% test coverage
• It highlights any requirements missing or document inconsistencies
• It shows the overall defects or execution status with a focus on business requirements
• It helps in analyzing or estimating the impact on the QA team's work with respect to
• revisiting or re-working on the test cases.

28 What is Test Coverage?


Test Coverage states which requirements of the customers are to be verified when the
testing phase starts. Test Coverage is a term that determines whether the test cases are
written and executed to ensure to test the software application completely, in such a
way that minimal or NIL defects are reported.

29 How to achieve Test Coverage?


The maximum Test Coverage can be achieved by establishing good ‘Requirement
Traceability’.
• Mapping all internal defects to the test cases designed
• Mapping all the Customer Reported Defects (CRD) to individual test cases for the
• future regression test suite.

30 Methods of Software Testing


There are 3 methods of software testing.
1) White box 2) Black box 3) Grey Box

31 What is White Box Testing?


White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on
applications internal code structure. In white-box testing, an internal perspective of the
system, as well as programming skills, are used to design test cases. This testing usually was
done at the unit level.
32 What is Black Box Testing?
Black Box Testing is a software testing method in which testers evaluate the functionality of the
software under test without looking at the internal code structure. This can be applied to every
level of software testing such as Unit, Integration, System and Acceptance Testing.

33 What is Grey Box Testing?


Grey box is the combination of both White Box and Black Box Testing. The tester who works on
this type of testing needs to have access to design documents. This helps to create better test
cases in this process.

34 What is Alpha Testing?


Alpha testing is done by the in-house developers (who developed the software) and testers.
Sometimes alpha testing is done by the client or outsourcing team with the presence of
developers or testers.
It has two phases:
• In the first phase of alpha testing, the software is tested by in-house developers. They
• use debugger software. The goal is to catch bugs quickly.
• In the second phase of alpha testing, the software is handed over to the software QA
• staff, for additional testing in an environment that is similar to the intended use.

35 What is Beta Testing?


Beta testing is done by a limited number of end users before delivery. Usually, it is done in
the client places.

36 What is Gamma Testing?


Gamma testing is done when the software is ready for release with specified requirements.
It is done at the client place. It is done directly by skipping all the in-house testing activities.

37 What is Functional Testing?


In simple words, what the system actually does is functional testing. To verify that each
function of the software application behaves as specified in the requirement document.
Testing all the functionalities by providing appropriate input to verify whether the actual
output is matching the expected output or not. It falls within the scope of black box testing
and the testers need not concern about the source code of the application.

37.1 What is Unit/Module Testing?


Unit Testing is also called as Module Testing or Component Testing. It is done to check
whether the individual unit or module of the source code is working properly. It is done
by the developers in the developer’s environment.

37.2 What is Integration Testing?


Integration Testing is the process of testing the interface between the two software
units. Integration testing is done by three ways. Big Bang Approach, Top-Down
Approach, Bottom-Up Approach.

37.3 What is System Testing?


Testing the fully integrated application to evaluate the system’s compliance with its
specified requirements is called System Testing End to End testing. Verifying the
completed system to ensure that the application works as intended or not.
System testing is carried out by specialist testers or independent testers.
System testing should investigate both functional and non-functional requirements of
the testing.

37.4 What is Smoke Testing?


Smoke Testing is done to make sure if the build we received from the development
team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It
helps not to waste the testing time to simply testing the whole application when the key
features don’t work or the key bugs have not been fixed yet.

37.5 What is Sanity Testing?


Sanity Testing is done during the release phase to check for the main functionalities of
the application without going deeper. It is also called as a subset of Regression testing. It
is done at the “release level”. We perform sanity testing when we don’t have enough
time for regression testing.

37.6 What is Regression Testing?


Repeated testing of an already tested program, after modification, to discover any
defects introduced or uncovered as a result of the changes in the software being tested
or in another related or unrelated software components.
Usually, we do regression testing in the following cases:
1. New functionalities are added to the application
2. Change Requirement (In organizations, we call it as CR)
3. Defect Fixing
4. Performance Issue Fix
5. Environment change (E.g., Updating the DB from MySQL to Oracle)
37.7 What is Retesting Testing?
Retesting is done to make sure that the tests cases which failed in last execution are
passed after the defects are fixed. Retesting is carried out based on the defect fixes. In
Retesting, the cases which are failed earlier can be included to check if the functionality
failure in an earlier build.

37.8 What is Exploratory Testing?


Usually, this process will be carried out by domain experts. They perform testing just by
exploring the functionalities of the application without having the knowledge of the
requirements.

38 What is Monkey Testing?


Perform abnormal action on the application deliberately in order to verify the stability of
the application.

39 What is Big Bang Approach?


Combining all the modules once and verifying the functionality after completion of
individual module testing.

40 What is Top-Down Approach?


Testing takes place from top to bottom. High-level modules are tested first and then lowlevel
modules and finally integrating the low-level modules to a high level to ensure the
system is working as intended. Stubs are used as a temporary module if a module is not
ready for integration testing.

41 What is Bottom-Up Approach?


It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up.
Lowest level modules are tested first and then high-level modules and finally integrating the
high-level modules to a low level to ensure the system is working as intended. Drivers are
used as a temporary module for integration testing.

42 What is User Acceptance Testing / UAT? imp


It is also known as pre-production testing. This is done by the end users along with the
testers to validate the functionality of the application. After successful acceptance
testing. Formal testing conducted to determine whether an application is developed as per
the requirement. It allows the customer to accept or reject the application. Types of
acceptance testing is Alpha, Beta & Gamma.
43 What is Positive and Negative Testing?
Positive Testing: It is to determine what system supposed to do. It helps to check
whether the application is justifying the requirements or not.
Negative Testing: It is to determine what system not supposed to do. It helps to find
the defects from the software.

44. What is Non-Functional Testing?


In simple words, how well the system performs is non-functionality testing. Nonfunctional
testing refers to various aspects of the software such as performance, load,
stress, scalability, security, compatibility etc., Main focus is to improve the user
experience on how fast the system responds to a request.

44.1. What is Performance Testing?


This type of testing determines or validates the speed, scalability, and/or stability
characteristics of the system or application under test. Performance is concerned with
achieving response times, throughput, and resource-utilization levels that meet the
performance objectives for the project or product.

44.2. What is Load Testing?


It is to verify that the system/application can handle the expected number of
transactions and to verify the system/application behavior under both normal and peak
load conditions.

44.3. What is Volume Testing?


It is to verify that the system/application can handle a large amount of data.

44.4. What is Stress Testing?


It is to verify the behavior of the system once the load increases more than its design
expectations.

44.5. What is Scalability Testing?


Scalability testing is a type of non-functional testing. It is to determine how the
application under test scales with increasing workload.

44.6. What is Concurrency Testing?


Concurrency testing means accessing the application at the same time by multiple users
to ensure the stability of the system. This is mainly used to identify deadlock issues.
44.7. What is GUI Testing?
Graphical User Interface Testing is to test the interface between the application and the
end user.

44.8. What is Recovery Testing?


Recovery testing is performed in order to determine how quickly the system can recover
after the system crash or hardware failure. It comes under the type of non-functional
testing.

44.9. What is Installation Testing?


It is to check whether the application is successfully installed and it is working as
expected after installation.

44.10. What is Formal Testing?


It is a process where the testers test the application by having pre-planned
procedures and proper documentation.

44.11. What is Risk Based Testing?


Identify the modules or functionalities which are most likely cause failures and then
testing those functionalities.

44.12. What is Compatibility Testing?


It is to deploy and check whether the application is working as expected in a different
combination of environmental components.

44.13. What is Usability Testing?


To verify whether the application is user-friendly or not and was comfortably used by an
end user or not. The main focus in this testing is to check whether the end user can
understand and operate the application easily or not. An application should be selfexploratory
and must not require training to operate it.

44.14. What is Security Testing?


Security testing is a process to determine whether the system protects data and
maintains functionality as intended.

45 What is Soak Testing?


Running a system at high load for a prolonged period of time to identify the
performance problems is called Soak or Endurance Testing.
46 What is Fuzz Testing?
Fuzz testing is used to identify coding errors and security loopholes in an application. By
inputting massive amount of random data to the system in an attempt to make it crash
to identify if anything breaks in the application.

47 What is Adhoc Testing?


Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In
Adhoc testing, testers randomly test the application without following any documents
and test design techniques. This testing is primarily performed if the knowledge of
testers in the application under test is very high. Testers randomly test the application
without any test cases or any business requirement document.

48 What is Interface Testing?


Interface testing is performed to evaluate whether two intended modules pass data and
communicate correctly to one another.

49 What is Reliability Testing?


Perform testing on the application continuously for long period of time in order to verify
the stability of the application.

50 What is Bucket Testing? imp


Bucket or Split testing is a method to compare two versions of an application against
each other to determine which one performs better.

51 What is Defect Cascading in Software Testing?


Defect cascading in Software testing means triggering of other defects in an application.
When a defect is not identified or goes unnoticed while testing, it invokes other defects.
It leads to multiple defects in the later stages and results in an increase in a number of
defects in the application.
For example, if there is a defect in an accounting system related to negative taxation
then the negative taxation defect affects the ledger which in turn affects other reports
such as Balance Sheet, Profit & Loss etc.,

52 What is Walk Through?


A walkthrough is an informal meeting conducts to learn, gain understanding, and find
defects. The author leads the meeting and clarifies the queries raised by the peers in the
meeting.
53 What is Inspection?
Inspection is a formal meeting lead by a trained moderator, certainly not by the author.
The document under inspection is prepared and checked thoroughly by the reviewers
before the meeting. In the inspection meeting, the defects found are logged and shared
with the author for appropriate actions. Post inspection, a formal follow-up process is
used to ensure a timely and corrective action.

54 Who are all involved in an inspection meeting?


Author, Moderator, Reviewer(s), Scribe/Recorder and Manager.

55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.

56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.

57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.

58 What is Bug Severity?


Bug/Defect severity can be defined as the impact of the bug on customer’s business. It
can be Critical, Major or Minor. In simple words, how much effect will be there on the
system because of a particular defect.

59 What is Bug Priority?


Defect priority can be defined as how soon the defect should be fixed. It gives the order
in which a defect should be resolved. Developers decide which defect they should take
up next based on the priority. It can be High, Medium or Low. Most of the times the
priority status is set based on the customer requirement.

60 Tell some examples of Bug Severity and Bug Priority?


High Priority & High Severity: Submit button is not working on a login page and
customers are unable to login to the application
Low Priority & High Severity: key feature failed but there’s no impact on customer
business, e.g., calculation fault in yearly report which end user won’t use on daily basis.
High Priority & Low Severity: Spelling mistake of a company name on the homepage
Low Priority & Low Severity: FAQ page takes a long time to load

61 What is a Critical Bug?


A critical bug is a show stopper which means a large piece of functionality or major
system component is completely broken and there is no workaround to move further.
For example, Due to a bug in one module, we cannot test the other modules because
that blocker bug has blocked other modules. Bugs which affect the customers’ business
are considered as critical.
Example:
1. “Sign In” button is not working on Gmail App and Gmail users are blocked to login to
their accounts.
2. An error message pops up when a customer clicks on transfer money button in a
Banking website.

62 What are entry criteria?


Entry criteria is a set of conditions that permits a task to perform, or in absence of any of
these conditions, the task cannot be performed.
• The requirement document should be available.
• Complete understanding of the application flow is required.
• The Test Plan Document should be ready.

63 What is exit criteria?


Exit criteria is a set of expectations; this should be met before concluding the STLC
phase.
• Test Cases should be written and reviewed.
• Test Data should be identified and ready.
• Test automation script should be ready if applicable.

64 What is the Test Management Reviews & Audit?


Management Review is also known as Software Quality Assurance or (SQA). It focuses
more on the software process rather than the software work products. Quality
Assurance is a set of activities designed to ensure that the project manager follows the
standard process which is already pre-defined. In other words, Quality Assurance makes
sure, the Test Manager is doing the right things in the right way.
An audit is the examination of the work products and related information to assesses
whether the standard process was followed or not.
65 What is the difference between functional and non-functional testing?
Functional Testing Non Functional Testing

Performed before non-functional testing Performed after functional testing

Based on customer requirements Based on customers’ expectations

Describes what the product does Describes how the product works

66 On what basis the acceptance plan is prepared?


Basically, the acceptance document is prepared using the following inputs.
• Requirement document: It specifies what exactly is needed in the project from the
customers perspective.
• Input from the customer: This can be discussions, informal talks, emails, etc.
• Project plan: The project plan prepared by the project manager also serves as good
input to finalize your acceptance test.

67 What is a Test Report? What does it include?


Test report is basically a document that includes a total summary of testing objectives,
activities, and results. It is very much required to reflect testing results and gives an opportunity
to estimate testing results quickly. It helps us to decide whether the product is ready for release
or not. It also helps us determine the current status of the project and the quality of the
product. A test report must include the following details:
• Test Objective
• Project Information
• Defect
• Test Summary
Software Testing Vocabulary:
YouTube Channel Link: https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1

Affinity Diagram: A group process that takes large amounts of language data, such as a list developed by
brainstorming, and divides it into categories.

Application: A single software product that may or may not fully support a business function.

Audit: This is an inspection/assessment activity that verifies compliance with plans, policies, and procedures,
and ensures that resources are conserved. Audit is a staff function; it serves as the "eyes and ears" of
management.

Backlog: Work waiting to be done; for IT this includes new systems to be developed and enhancements to
existing systems. To be included in the development backlog, the work must have been cost-justified and
approved for development.

Baseline: A quantitative measure of the current level of performance.

Benchmarking: Comparing your company’s products, services, or processes against best practices, or
competitive practices, to help define superior performance of a product, service, or support process.

Black-box Testing: A test technique that focuses on testing the functionality of the program, component, or
application against its specifications without knowledge of how the system is constructed; usually data or
business process driven.

Boundary Value Analysis: A data selection technique in which test data is chosen from the “boundaries” of the
input or output domain classes, data structures, and procedure parameters. Choices often include the actual
minimum and maximum boundary values, the maximum value plus or minus one, and the minimum value plus
or minus one.

Brainstorming: A group process for generating creative and diverse ideas.

Branch Testing: A test method that requires that each possible branch on each decision point be executed at
least once.

Bug: A general term for all software defects or errors.

Candidate: An individual who has met eligibility requirements for a credential awarded through a certification
program, but who has not yet earned that certification through participation in the required skill and
knowledge assessment instruments.

Cause-Effect Graphing: A tool used to derive test cases from specifications. A graph that relates causes (or
input conditions) to effects is generated. The information in the graph is converted into a decision table where
the columns are the cause-effect combinations. Unique rows represent test cases.

Certification: A voluntary process instituted by a nongovernmental agency by which individual applicants are
recognized for having achieved a measurable level of skill or knowledge. Measurement of the skill or
knowledge makes certification more restrictive than simple registration, but much less restrictive than formal
licensure.

Checklists: A series of probing questions about the completeness and attributes of an application system.
Well-constructed checklists cause evaluation of areas, which are prone to problems. It both limits the scope of
the test and directs the tester to the areas in which there is a high probability of a problem.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Checkpoint Review: Held at predefined points in the development process to evaluate whether certain quality
factors (critical success factors) are being adequately addressed in the system being built. Independent experts
for the purpose of identifying problems conduct the reviews as early as possible.

Check sheet: A form used to record data as it is gathered.

Client: The customer that pays for the product received and receives the benefit from the use of the product.

Coaching: Providing advice and encouragement to an individual or individuals to promote a desired behaviour.

Code Comparison: One version of source or object code is compared to a second version. The objective is to
identify those portions of computer programs that have been changed. The technique is used to identify those
segments of an application program that have been altered as a result of a program change.

Compiler-Based Analysis: Most compilers for programming languages include diagnostics that identify
potential program structure flaws. Many of these diagnostics are warning messages requiring the programmer
to conduct additional investigation to determine whether or not the problem is real. Problems may include
syntax problems, command violations, or variable/data reference problems. These diagnostic messages are a
useful means of detecting program problems, and should be used by the programmer.

Complete Test Set: A test set containing data that causes each element of pre-specified set of Boolean
conditions to be true. In addition, each element of the test set causes at least one condition to be true.

Completeness: The property that all necessary parts of an entity are included. Often, a product is said to be
complete if it has met all requirements.

Complexity-Based Analysis: Based upon applying mathematical graph theory to programs and preliminary
design language specification (PDLs) to determine a unit's complexity. This analysis can be used to measure
and control complexity when maintainability is a desired attribute. It can also be used to estimate test effort
required and identify paths that must be tested.

Compliance Checkers: A parse program looking for violations of company standards. Statements that contain
violations are flagged. Company standards are rules that can be added, changed, and deleted as needed.

Condition Coverage: A white-box testing technique that measures the number of, or percentage of, decision
outcomes covered by the test cases designed. 100% condition coverage would indicate that every possible
outcome of each decision had been executed at least once during testing.

Configuration Management Tools: Tools that are used to keep track of changes made to systems and all
related artifacts. These are also known as version control tools.

Configuration Testing: Testing of an application on all supported hardware and software platforms. This may
include various combinations of hardware types, configuration settings, and software versions.

Consistency: The property of logical coherence among constituent parts. Consistency can also be expressed as
adherence to a given set of rules.

Consistent Condition Set: A set of Boolean conditions such that complete test sets for the conditions uncover
the same errors.

Control Flow Analysis: Based upon graphical representation of the program process. In control flow analysis,
the program graph has nodes, which represent a statement or segment possibly ending in an unresolved
branch. The graph illustrates the flow of program control from one segment to another as illustrated through
branches. The objective of control flow analysis is to determine potential problems in logic branches that
might result in a loop condition or improper processing.

Conversion Testing: Validates the effectiveness of data conversion processes, including field-to field mapping,
and data translation.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Correctness: The extent to which software is free from design and coding defects (i.e., faultfree). It is also the
extent to which software meets its specified requirements and user objectives.

Cost of Quality (COQ): Money spent beyond expected production costs (labor, materials, equipment) to
ensure that the product the customer receives is a quality (defect free) product. The Cost of Quality includes
prevention, appraisal, and correction or repair costs.

Coverage-Based Analysis: A metric used to show the logic covered during a test session, providing insight to
the extent of testing. The simplest metric for coverage would be the number of computer statements
executed during the test compared to the total number of statements in the program. To completely test the
program structure, the test data chosen should cause the execution of all paths. Since this is not generally
possible outside of unit test, general metrics have been developed which give a measure of the quality of test
data based on the proximity to this ideal coverage. The metrics should take into consideration the existence of
infeasible paths, which are those paths in the program that have been designed so that no data will cause the
execution of those paths.

Customer: The individual or organization, internal or external to the producing organization that receives the
product.

Data Dictionary: Provides the capability to create test data to test validation for the defined data elements.
The test data generated is based upon the attributes defined for each data element. The test data will check
both the normal variables for each data element as well as abnormal or error conditions for each data
element.

DD (decision-to-decision) path: A path of logical code sequence that begins at a decision statement or an
entry and ends at a decision statement or an exit.

Debugging: The process of analysing and correcting syntactic, logic, and other errors identified during testing.

Decision Coverage: A white-box testing technique that measures the number of, or percentage of, decision
directions executed by the test case designed. 100% decision coverage would indicate that all decision
directions had been executed at least once during testing. Alternatively, each logical path through the program
can be tested. Often, paths through the program are grouped into a finite set of classes, and one path from
each class is tested.

Decision Table: A tool for documenting the unique combinations of conditions and associated results in order
to derive unique test cases for validation testing.

Defect: Operationally, it is useful to work with two definitions of a defect: 1. From the producer's viewpoint a
defect is a product requirement that has not been met or a product attribute possessed by a product or a
function performed by a product that is not in the statement of requirements that define the product; 2. From
the customer's viewpoint a defect is anything that causes customer dissatisfaction, whether in the statement
of requirements or not.

Defect Tracking Tools: Tools for documenting defects as they are found during testing and for tracking their
status through to resolution.

Design Level: The design decomposition of the software item (e.g., system, subsystem, program, or module).

Desk Checking: The most traditional means for analysing a system or a program. Desk checking is conducted
by the developer of a system or program. The process involves reviewing the complete product to ensure that
it is structurally sound and that the standards and requirements have been met. This tool can also be used on
artifacts created during analysis and design.

Driver: Code that sets up an environment and calls a module for test.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Dynamic Analysis: Analysis performed by executing the program code. Dynamic analysis executes or simulates
a development phase product, and it detects errors by analysing the response of a product to sets of input
data.

Dynamic Assertion: A dynamic analysis technique that inserts into the program code assertions about the
relationship between program variables. The truth of the assertions is determined as the program executes.

Empowerment: Giving people the knowledge, skills, and authority to act within their area of expertise to do
the work and improve the process.

Entrance Criteria: Required conditions and standards for work product quality that must be present or met for
entry into the next stage of the software development process.

Equivalence Partitioning: The input domain of a system is partitioned into classes of representative values so
that the number of test cases can be limited to one-per-class, which represents the minimum number of test
cases that must be executed.

Error or Defect: 1. A discrepancy between a computed, observed, or measured value or condition and the
true, specified, or theoretically correct value or condition. Human action that results in software containing a
fault (e.g., omission or misinterpretation of user requirements in a software specification, incorrect translation,
or omission of a requirement in the design specification).

Error Guessing: Test data selection technique for picking values that seem likely to cause defects. This
technique is based upon the theory that test cases and test data can be developed based on the intuition and
experience of the tester.

Exhaustive Testing: Executing the program through all possible combinations of values for program variables.

Exit Criteria: Standards for work product quality, which block the promotion of incomplete or defective work
products to subsequent stages of the software development process.

File Comparison: Useful in identifying regression errors. A snapshot of the correct expected results must be
saved so it can be used for later comparison.

Flowchart Pictorial: representations of data flow and computer logic. It is frequently easier to understand and
assess the structure and logic of an application system by developing a flow chart than to attempt to
understand narrative descriptions or verbal explanations. The flowcharts for systems are normally developed
manually, while flowcharts of programs can be produced.

Force Field Analysis: A group technique used to identify both driving and restraining forces that influence a
current situation.

Formal Analysis: Technique that uses rigorous mathematical techniques to analyse the algorithms of a solution
for numerical properties, efficiency, and correctness.

Functional Testing: Application of test data derived from the specified functional requirements without regard
to the final program structure.

Histogram: A graphical description of individually measured values in a data set that is organized according to
the frequency or relative frequency of occurrence. A histogram illustrates the shape of the distribution of
individual values in a data set along with information regarding the average and variation.

Infeasible Path: A sequence of program statements that can never be executed. Inputs Materials, services, or
information needed from suppliers to make a process work, or build a product.

Inspection: A formal assessment of a work product conducted by one or more qualified independent
reviewers to detect defects, violations of development standards, and other problems. Inspections involve
authors only when specific questions concerning deliverables exist. An inspection identifies defects, but does
not attempt to correct them. Authors take corrective actions and arrange follow-up reviews as needed.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Instrumentation: The insertion of additional code into a program to collect information about program
behaviour during program execution.

Integration Testing: This test begins after two or more programs or application components have been
successfully unit tested. It is conducted by the development team to validate the technical quality or design of
the application. It is the first level of testing which formally integrates a set of programs that communicate
among themselves via messages or files (a client and its server(s), a string of batch programs, or a set of online
modules within a dialog or conversation.)

Invalid Input: Test data that lays outside the domain of the function the program represents.

Leadership: The ability to lead, including inspiring others in a shared vision of what can be, taking risks, serving
as a role model, reinforcing and rewarding the accomplishments of others, and helping others to act.

Life Cycle Testing: The process of verifying the consistency, completeness, and correctness of software at each
stage of the development life cycle.

Management: A team or individuals who manage(s) resources at any level of the organization.

Mapping: Provides a picture of the use of instructions during the execution of a program. Specifically, it
provides a frequency listing of source code statements showing both the number of times an instruction was
executed and which instructions were not executed. Mapping can be used to optimize source code by
identifying the frequently used instructions. It can also be used to determine unused code, which can
demonstrate code, which has not been tested, code that is infrequently used, or code that is non-entrant.

Mean: A value derived by adding several quantities and dividing the sum by the number of these quantities.

Metric-Based Test Data Generation: The process of generating test sets for structural testing based on use of
complexity or coverage metrics.

Model Animation: It verifies that early models can handle the various types of events found in production
data. This is verified by “running” actual production transactions through the models as if they were
operational systems.

Model Balancing: Model balancing relies on the complementary relationships between the various models
used in structured analysis (event, process, data) to ensure that modelling rules/standards have been
followed; this ensures that these complementary views are consistent and complete.

Mutation Analysis: A method to determine test set thoroughness by measuring the extent to which a test set
can discriminate the program from slight variants (i.e., mutants) of it.

Network Analysers: A tool used to assist in detecting and diagnosing network problems. Outputs Products,
services, or information supplied to meet customer needs. Pass/Fail Criteria Decision rules used to determine
whether a software item or feature passes or fails a test.

Path Expressions: A sequence of edges from the program graph that represents a path through the program.

Path Testing: A test method satisfying the coverage criteria that each logical path through the program be
tested. Often, paths through the program are grouped into a finite set of classes and one path from each class
is tested.

Performance Test: Validates that both the online response time and batch run times meet the defined
performance requirements.

Performance/Timing Analyzer: A tool to measure system performance. Phase (or Stage) Containment A
method of control put in place within each stage of the development process to promote error identification
and resolution so that defects are not propagated downstream to subsequent stages of the development
process. The verification, validation, and testing of work within the stage that it is created. Policy Managerial
desires and intents concerning either process (intended objectives) or products (desired attributes).

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Population Analysis: Analyses production data to identify, independent from the specifications, the types and
frequency of data that the system will have to process/produce. This verifies that the specs can handle types
and frequency of actual data and can be used to create validation tests.

Procedure: The step-by-step method followed to ensure that standards are met. The work effort that
produces a product. This includes efforts of people and equipment guided by policies, standards, and
procedures. 2. The process or set of processes used by an organization or project to plan, manage, execute,
monitor, control, and improve its software related activities. A set of activities and tasks. A statement of
purpose and an essential set of practices (activities) that address that purpose.

Process Improvement: To change a process to make the process produce a given product faster, more
economically, or of higher quality. Such changes may require the product to be changed. The defect rate must
be maintained or reduced.

Product: The output of a process: the work product. There are three useful classes of products: Manufactured
Products (standard and custom), Administrative/Information Products (invoices, letters, etc.), and Service
Products (physical, intellectual, physiological, and psychological). A statement of requirements defines
products; one or more people working in a process produce them.

Product Improvement: To change the statement of requirements that defines a product to make the product
more satisfying and attractive to the customer (more competitive). Such changes may add to or delete from
the list of attributes and/or the list of functions defining a product. Such changes frequently require the
process to be changed. Note: This process could result in a very new product.

Production Costs: The cost of producing a product. Production costs, as currently reported, consist of (at least)
two parts; actual production or right-the-first time costs (RFT) plus the Cost of Quality (COQ). RFT costs include
labor, materials, and equipment needed to provide the product correctly the first time.

Productivity: The ratio of the output of a process to the input, usually measured in the same units. It is
frequently useful to compare the value added to a product by a process, to the value of the input resources
required (using fair market values for both input and output).

Proof of Correctness: The use of mathematical logic techniques to show that a relationship between program
variables assumed true at program entry implies that another relationship between program variables holds at
program exit.

Quality: A product is a quality product if it is defect free. To the producer, a product is a quality product if it
meets or conforms to the statement of requirements that defines the product. This statement is usually
shortened to: quality means meets requirements. From a customer’s perspective, quality means “fit for use.”

Quality Assurance (QA): The set of support activities (including facilitation, training, measurement, and
analysis) needed to provide adequate confidence that processes are established and continuously improved to
produce products that meet specifications and are fit for use.

Quality Control (QC): The process by which product quality is compared with applicable standards, and the
action taken when nonconformance is detected. Its focus is defect detection and removal. This is a line
function; that is, the performance of these tasks is the responsibility of the people working within the process.

Quality Function Deployment (QFD): A systematic matrix method used to translate customer wants or needs
into product or service characteristics that will have a significant positive impact on meeting customer
demands.

Quality Improvement: To change a production process so that the rate at which defective products (defects)
are produced is reduced. Some process changes may require the product to be changed.

Recovery Test: Evaluates the contingency features built into the application for handling interruptions and for
returning to specific points in the application processing cycle, including checkpoints, backups, restores, and
restarts. This test also assures that disaster recovery is possible.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Regression Testing: Testing of a previously verified program or application following program modification for
extension or correction to ensure no new defects have been introduced.

Requirement: A formal statement of: 1. An attribute to be possessed by the product or a function to be


performed by the product 2. The performance standard for the attribute or function; and/or 3. The measuring
process to be used in verifying that the standard has been met.

Risk Matrix: Shows the controls within application systems used to reduce the identified risk, and in what
segment of the application those risks exist. One dimension of the matrix is the risk, the second dimension is
the segment of the application system, and within the matrix at the intersections are the controls. For
example, if a risk is “incorrect input” and the systems segment is “data entry,” then the intersection within the
matrix would show the controls designed to reduce the risk of incorrect input during the data entry segment of
the application system.

Run Chart: A graph of data points in chronological order used to illustrate trends or cycles of the characteristic
being measured to suggest an assignable cause rather than random variation.

Self-validating Code: Code that makes an explicit attempt to determine its own correctness and to proceed
accordingly. Simulation Use of an executable model to represent the behaviour of an object. During testing,
the computational hardware, the external environment, and even code segments may be simulated.

Software Feature: A distinguishing characteristic of a software item (e.g., performance, portability, or


functionality). Software Item Source code, object code, job control code, control data, or a collection of these.

Special Test Data: Test data based on input values that are likely to require special handling by the program.
Standardize Procedures that are implemented to ensure that the output of a process is maintained at a desired
level.

Standards: The measure used to evaluate products and identify nonconformance. The basis upon which
adherence to policies is measured.

Statement of Requirements: The exhaustive list of requirements that define a product. Note that the
statement of requirements should document requirements proposed and rejected (including the reason for
the rejection) during the requirement determination process.

Statement Testing: A test method that executes each statement in a program at least once during program
testing. Static

Analysis: Analysis of a program that is performed without executing the program. It may be applied to the
requirements, design, or code. Statistical Process Control The use of statistical techniques and tools to
measure an ongoing process for change or stability.

Stress Testing: This test subjects a system, or components of a system, to varying environmental conditions
that defy normal expectations. For example, high transaction volume, large database size or restart/recovery
circumstances. The intention of stress testing is to identify constraints and to ensure that there are no
performance problems.

Structural Testing: A testing method in which the test data is derived solely from the program structure. Stub
Special code segments that when invoked by a code segment under testing, simulate the behaviour of
designed and specified modules not yet constructed.

Supplier: An individual or organization that supplies inputs needed to generate a product, service, or
information to a customer.

Symbolic Execution: A method of symbolically defining data that forces program paths to be executed. Instead
of executing the program with actual data values, the variable names that hold the input values are used.
Thus, all variable manipulations and decisions are made symbolically. This process is used to verify the
completeness of the structure, as opposed to assessing the functional requirements of the program.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
System: One or more software applications that together support a business function.

System Test: During this event, the entire system is tested to verify that all functional, information, structural
and quality requirements have been met. A predetermined combination of tests is designed that, when
executed successfully, satisfy management that the system meets specifications. System testing verifies the
functional quality of the system in addition to all external interfaces, manual procedures, restart and recovery,
and human-computer interfaces. It also verifies that interfaces between the application and the open
environment work correctly, that JCL functions correctly, and that the application functions appropriately with
the Database Management System, Operations environment, and any communications systems.

Test: 1. A set of one or more test cases. 2. A set of one or more test cases and procedures.

Test Case Generator: A software tool that creates test cases from requirements specifications. Cases
generated this way ensure that 100% of the functionality specified is tested.

Test Case Specification: An individual test condition, executed as part of a larger test that contributes to the
test’s objectives. Test cases document the input, expected results, and execution conditions of a given test
item. Test cases are broken down into one or more detailed test scripts and test data conditions for execution.

Test Cycle: Test cases are grouped into manageable (and schedulable) units called test cycles. Grouping is
according to the relation of objectives to one another, timing requirements, and on the best way to expedite
defect detection during the testing event. Often test cycles are linked with execution of a batch process.

Test Data Generator: A software package that creates test transactions for testing application systems and
programs. The type of transactions that can be generated is dependent upon the options available in the test
data generator. With many current generators, the prime advantage is the ability to create a large number of
transactions to volume test application systems.

Test Data Set: Set of input elements used in the testing process.

Test Design Specification: A document that specifies the details of the test approach for a software feature or
a combination of features and identifies the associated tests.

Test Driver: A program that directs the execution of another program against a collection of test data sets.
Usually, the test driver also records and organizes the output generated as the tests are run. Test Harness A
collection of test drivers and test stubs.

Test Incident Report: A document describing any event during the testing process that requires investigation.

Test Item: A software item that is an object of testing. Test Item Transmittal Report A document that identifies
test items and includes status and location information.

Test Log: A chronological record of relevant details about the execution of tests.

Test Plan: A document describing the intended scope, approach, resources, and schedule of testing activities.
It identifies test items, the features to be tested, the testing tasks, the personnel performing each task, and
any risks requiring contingency planning.

Test Procedure: Specification A document specifying a sequence of actions for the execution of a test.

Test Scripts: A tool that specifies an order of actions that should be performed during a test session. The script
also contains expected results. Test scripts may be manually prepared using paper forms, or may be
automated using capture/playback tools or other kinds of automated scripting tools.

Test Stubs: Simulates a called routine so that the calling routine’s functions can be tested. A test harness (or
driver) simulates a calling component or external environment, providing input to the called routine, initiating
the routine, and evaluating or displaying output returned.

Test Suite Manager: A tool that allows testers to organize test scripts by function or other grouping.

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Test Summary Report: A document that describes testing activities and results and evaluates the
corresponding test items.

Tracing: A process that follows the flow of computer logic at execution time. Tracing demonstrates the
sequence of instructions or a path followed in accomplishing a given task. The two main types of trace are
tracing instructions in computer programs as they are executed, or tracing the path through a database to
locate predetermined pieces of information.

Unit Test: Testing individual programs, modules, or components to demonstrate that the work package
executes per specification, and validate the design and technical quality of the application. The focus is on
ensuring that the detailed logic within the component is accurate and reliable according to pre-determined
specifications. Testing stubs or drivers may be used to simulate behaviour of interfacing modules.

Usability Test: The purpose of this event is to review the application user interface and other human factors of
the application with the people who will be using the application. This is to ensure that the design (layout and
sequence, etc.) enables the business functions to be executed as easily and intuitively as possible. This review
includes assuring that the user interface adheres to documented User Interface standards, and should be
conducted early in the design stage of development. Ideally, an application prototype is used to walk the client
group through various business scenarios, although paper copies of screens, windows, menus, and reports can
be used.

User: The customer that actually uses the product received.

User Acceptance Test: User Acceptance Testing (UAT) is conducted to ensure that the system meets the needs
of the organization and the end user/customer. It validates that the system will work as intended by the user
in the real world, and is based on real world business scenarios, not system requirements. Essentially, this test
validates that the right system was built.

Valid Input: Test data that lie within the domain of the function represented by the program.

Validation: Determination of the correctness of the final program or software produced from a development
project with respect to the user needs and requirements. Validation is usually accomplished by verifying each
stage of the software development life cycle.

Values (Sociology): The ideals, customs, instructions, etc., of a society toward which the people have an
affective regard. These values may be positive, as cleanliness, freedom, or education, or negative, as cruelty,
crime, or blasphemy. Any object or quality desired as a means or as an end in itself.

Verification: 1. The process of determining whether the products of a given phase of the software
development cycle fulfil the requirements established during the previous phase. 2. The act of reviewing,
inspecting, testing, checking, auditing, or otherwise establishing and documenting whether items, processes,
services, or documents conform to specified requirements.

Vision: A vision is a statement that describes the desired future state of a unit.

Walkthroughs: During a walkthrough, the producer of a product “walks through” or paraphrases the products
content, while a team of other individuals follow along. The team’s job is to ask questions and raise issues
about the product that may lead to defect identification.

White-box Testing: A testing technique that assumes that the path of the logic in a program unit or
component is known. White-box testing usually consists of testing paths, branch by branch, to produce
predictable results. This technique is usually used during tests executed by the development team, such as
Unit or Component testing,

https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
SQL BASICS AND
ADVANCED
INTRODUCTION
SQL is a standard language for accessing databases.

how to use SQL to access and manipulate data in:

MySQL, SQL Server, Access, Oracle, Sybase, DB2, and other database systems.

SQL Syntax:

SELECT Company, Country FROM Customers WHERE Country <> 'USA'

SQL Result:

Company Country

Island Trading UK
Galería del gastrónomo Spain
Laughing Bacchus Wine Cellars Canada
Paris spécialités France
Simons bistro Denmark
Wolski Zajazd Poland

SQL is a “standard language for accessing and manipulating databases”.

What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
 SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

2
RDBMS

 RDBMS stands for Relational Database Management System.


 RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
 The data in RDBMS is stored in database objects called tables.
 A table is a collections of related data entries and it consists of columns and rows.

SQL BASICS
Database Tables

A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers"
or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and five columns (P_Id, LastName,
FirstName, Address, and City).

SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement will select all the records in the "Persons" table:

SELECT * FROM Persons

Note:
• SQL is not case sensitive
• Semicolon after SQL Statements?
• Some database systems require a semicolon at the end of each SQL statement.
• Semicolon is the standard way to separate each SQL statement in database systems that allow
more than one SQL statement to be executed in the same call to the server.
• We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each
SQL statement, but some database programs force you to use it.

3
SQL DML and DDL

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition
Language (DDL).

The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),
specify links between tables, and impose constraints between tables. The most important DDL statements
in SQL are:

CREATE DATABASE - creates a new database


ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

The SQL SELECT Statement

 The SELECT statement is used to select data from a database.


 The result is stored in a result table, called the result-set.

 SQL SELECT Syntax

SELECT column_name(s)
FROM table_name
And
SELECT * FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

An SQL SELECT Example


The "Persons" table:

4
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the columns named "LastName" and "FirstName" from the table
above.

We use the following SELECT statement:

SELECT LastName,FirstName FROM Persons

The result-set will look like this:

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SELECT * Example

Now we want to select all the columns from the "Persons" table.
We use the following SELECT statement:

SELECT * From Persons

The SQL SELECT DISTINCT Statement

 In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.
 The DISTINCT keyword can be used to return only distinct (different) values.

 SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name(s)


FROM table_name

SELECT DISTINCT Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

5
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the distinct values from the column named "City" from the table above.
We use the following SELECT statement:

SELECT DISTINCT City FROM Persons

The result-set will look like this:

City
Sandnes
Stavanger

The WHERE Clause

 The WHERE clause is used to filter records.


 The WHERE clause is used to extract only those records that fulfill a specified criterion.
 SQL WHERE Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator value

WHERE Clause Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement:

SELECT * FROM Persons


WHERE City='Sandnes'

6
The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Quotes Around Text Fields

SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.

For text values:

This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove

For numeric values:

This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause

With the WHERE clause, the following operators can be used:

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns

Note: In some versions of SQL the <> operator may be written as !=

7
The AND & OR Operators
 The AND & OR operators are used to filter records based on more than one condition.
 The AND operator displays a record if both the first condition and the second condition is true.
 The OR operator displays a record if either the first condition or the second condition is true.

AND Operator Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to
"Svendson":

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName='Tove'AND LastName='Svendson'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes

OR Operator Example

Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to
"Ola":

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName='Tove' OR FirstName='Ola'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

8
2 Svendson Tove Borgvn 23 Sandnes
Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).

Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal
to "Tove" OR to "Ola":

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola')

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes

The ORDER BY Keyword


 The ORDER BY keyword is used to sort the result-set.
 The ORDER BY keyword is used to sort the result-set by a specified column.
 The ORDER BY keyword sort the records in ascending order by default.
 If you want to sort the records in a descending order, you can use the DESC keyword.
 SQL ORDER BY Syntax

SELECT column_name(s)
FROM table_name ORDER BY column_name(s) ASC|DESC

ORDER BY Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
Now we want to select all the persons from the table above, however, we want to sort the persons by their
last name.

We use the following SELECT statement:

SELECT * FROM Persons ORDER BY LastName

9
The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
4 Nilsen Tom Vingvn 23 Stavanger
3 Pettersen Kari Storgt 20 Stavanger
2 Svendson Tove Borgvn 23 Sandnes

ORDER BY DESC Example

Now we want to select all the persons from the table above, however, we want to sort the persons
descending by their last name.

We use the following SELECT statement:

SELECT * FROM Persons ORDER BY LastName DESC

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
1 Hansen Ola Timoteivn 10 Sandnes

The INSERT INTO Statement


 The INSERT INTO statement is used to insert new records in a table.
 The INSERT INTO statement is used to insert a new row in a table.
 SQL INSERT INTO Syntax
 It is possible to write the INSERT INTO statement in two forms.
 The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name VALUES (value1, value2, value3,...)

 The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2,


value3,...)

10
SQL INSERT INTO Example

We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to insert a new row in the "Persons" table.

We use the following SQL statement:

INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger

Insert Data Only in Specified Columns


It is also possible to only add data in specific columns.

The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the
"FirstName" columns:

INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob

The UPDATE Statement

11
 The UPDATE statement is used to update records in a table.
 The UPDATE statement is used to update existing records in a table.
 SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!

SQL UPDATE Example


The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob

Now we want to update the person "Tjessem, Jakob" in the "Persons" table.

We use the following SQL statement:

UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

SQL UPDATE Warning

12
Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:

UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'

The "Persons" table would have looked like this:

P_Id LastName FirstName Address City


1 Hansen Ola Nissestien 67 Sandnes
2 Svendson Tove Nissestien 67 Sandnes
3 Pettersen Kari Nissestien 67 Sandnes
4 Nilsen Johan Nissestien 67 Sandnes
5 Tjessem Jakob Nissestien 67 Sandnes

The DELETE Statement


 The DELETE statement is used to delete records in a table.
 The DELETE statement is used to delete rows in a table.
 SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!

SQL DELETE Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.

We use the following SQL statement:

13
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger

Delete All Rows

It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:

DELETE FROM table_name

or

DELETE * FROM table_name

SQL ADVANCE

The TOP Clause


 The TOP clause is used to specify the number of records to return.
 The TOP clause can be very useful on large tables with thousands of records. Returning a large
number of records can impact on performance.

Note: Not all database systems support the TOP clause.

 SQL Server Syntax:


SELECT TOP number|percent column_name(s)
FROM table_name

 SQL SELECT TOP Equivalent in MySQL and Oracle:

• MySQL Syntax:
SELECT column_name(s)
FROM table_name
LIMIT number

14
Example:
SELECT *
FROM Persons
LIMIT 5

• Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number

Example
SELECT *
FROM Persons
WHERE ROWNUM <=5

SQL TOP Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

Now we want to select only the two first records in the table above.

We use the following SELECT statement:

SELECT TOP 2 * FROM Persons

The result-set will look like this:

P_Id LastName FirstName Address City

15
1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

SQL TOP PERCENT Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

Now we want to select only 50% of the records in the table above.

We use the following SELECT statement:

SELECT TOP 50 PERCENT * FROM Persons

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

SQL Wildcards
 SQL wildcards can be used when searching for data in a database.
 SQL wildcards can substitute for one or more characters when searching for data in a database.

16
 SQL wildcards must be used with the SQL LIKE operator.
 With SQL, the following wildcards can be used:

Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] Any single character not in charlist

or

[!charlist]

SQL Wildcard Examples


We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Using the % Wildcard


Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE 'sa%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons"
table.

We use the following SELECT statement:

17
SELECT * FROM Persons
WHERE City LIKE '%nes%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Using the _ Wildcard


Now we want to select the persons with a first name that starts with any character, followed by "la" from
the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE FirstName LIKE '_la'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE 'S_end_on'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard


Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the "Persons"
table.

18
We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE '[bsp]%'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName LIKE '[!bsp]%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

The LIKE Operator


 The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
 The LIKE operator is used to search for a specified pattern in a column.

 SQL LIKE Syntax:


SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

LIKE Operator Example


The "Persons" table:

19
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons living in a city that starts with "s" from the table above.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE 's%'

The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the
pattern.

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE '%s'

The result-set will look like this:

P_Id LastName FirstName Address City

20
1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "tav" from the "Persons"
table.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City LIKE '%tav%'

The result-set will look like this:

P_Id LastName FirstName Address City

3 Pettersen Kari Storgt 20 Stavanger

It is also possible to select the persons living in a city that NOT contains the pattern "tav" from the
"Persons" table, by using the NOT keyword.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE City NOT LIKE '%tav%'

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

The IN Operator
 The IN operator allows you to specify multiple values in a WHERE clause.

21
 SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

IN Operator Example
The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table
above.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName IN ('Hansen','Pettersen')

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The BETWEEN Operator

22
 The BETWEEN operator is used in a WHERE clause to select a range of data between two
values.
 The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.

 SQL BETWEEN Syntax:


SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

BETWEEN Operator Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen"
from the table above.

We use the following SELECT statement:

SELECT * FROM Persons


WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

Note:

23
The BETWEEN operator is treated differently in different databases.

In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed, because the
BETWEEN operator only selects fields that are between and excluding the test values).

In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because the
BETWEEN operator selects fields that are between and including the test values).

And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen" will not be
listed (like the example above), because the BETWEEN operator selects fields between the test values,
including the first test value and excluding the last test value.

Therefore: Check how your database treats the BETWEEN operator.

Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:

SELECT * FROM Persons


WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SQL Alias
 With SQL, an alias name can be given to a table or to a column.
 You can give a table or a column another name by using an alias. This can be a good thing to do if
you have very long or complex table names or column names.

 An alias name could be anything, but usually it is short.

 SQL Alias Syntax for Tables:


SELECT column_name(s)
FROM table_name
AS alias_name

 SQL Alias Syntax for Columns:


SELECT column_name AS alias_name
FROM table_name

24
Alias Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the
table aliases of "p" and "po" respectively.

Now we want to list all the orders that "Ola Hansen" is responsible for.

We use the following SELECT statement:

SELECT po.OrderID, p.LastName, p.FirstName


FROM Persons AS p, Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola'

The same SELECT statement without aliases:

SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName


FROM Persons, Product_Orders
WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'

Notes: As you'll see from the two SELECT statements above; aliases can make queries easier to both
write and to read.

SQL JOIN
 SQL joins are used to query data from two or more tables, based on a relationship between certain
columns in these tables.
 The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
 Tables in a database are often related to each other with keys.
 A primary key is a column (or a combination of columns) with a unique value for each row. Each
primary key value must be unique within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.

Look at the "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can
have the same P_Id. The P_Id distinguishes two persons even if they have the same name.

25
Next, we have the "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to
the persons in the "Persons" table without using their names.

Notice that the relationship between the two tables above is the "P_Id" column.

Different SQL JOINs


Before we continue with examples, we will list the types of JOIN you can use, and the differences
between them.

• JOIN: Return rows when there is at least one match in both tables
• LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table

• RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table

• FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN Keyword


 The INNER JOIN keyword return rows when there is at least one match in both tables.

 SQL INNER JOIN Syntax:


SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

 PS: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

26
2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

Now we want to list all the persons with any orders.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo


FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows
in "Persons" that do not have matches in "Orders", those rows will NOT be listed.

27
SQL LEFT JOIN Keyword
 The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table (table_name2).

 SQL LEFT JOIN Syntax:


SELECT column_name(s)
FROM table_name1 LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

 PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

Now we want to list all the persons and their orders - if any, from the tables above.

28
We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo


FROM Persons LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

Svendson Tove

Notes: The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).

SQL RIGHT JOIN Keyword


 The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are
no matches in the left table (table_name1).

 SQL RIGHT JOIN Syntax:


SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

 PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

29
SQL RIGHT JOIN Example
The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

Now we want to list all the orders with containing persons - if any, from the tables above.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo


FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

The result-set will look like this:

30
LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

34764

Notes: The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no
matches in the left table (Persons).

SQL FULL JOIN Keyword


 The FULL JOIN keyword return rows when there is a match in one of the tables.

 SQL FULL JOIN Syntax:


SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN Example


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id

31
1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15

Now we want to list all the persons and their orders, and all the orders with their persons.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo

FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

Svendson Tove

34764

Notes: The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from
the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.

The SQL UNION Operator

32
 The UNION operator is used to combine the result-set of two or more SELECT statements.
 Notice that each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types. Also, the columns in each SELECT statement
must be in the same order.

 SQL UNION Syntax:


SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL.

 SQL UNION ALL Syntax:


SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

 PS: The column names in the result-set of a UNION are always equal to the column names in the
first SELECT statement in the UNION.

SQL UNION Example


Look at the following tables:

"Employees_Norway":

E_ID E_Name

01 Hansen, Ola

02 Svendson, Tove

03 Svendson, Stephen

04 Pettersen, Kari

"Employees_USA":

E_ID E_Name

01 Turner, Sally

33
02 Kent, Clark

03 Svendson, Stephen

04 Scott, Stephen

Now we want to list all the different employees in Norway and USA.

We use the following SELECT statement:

SELECT E_Name FROM Employees_Norway


UNION
SELECT E_Name FROM Employees_USA

The result-set will look like this:

E_Name

Hansen, Ola

Svendson, Tove

Svendson, Stephen

Pettersen, Kari

Turner, Sally

Kent, Clark

Scott, Stephen

Note: This command cannot be used to list all employees in Norway and USA. In the example above we
have two employees with equal names, and only one of them will be listed. The UNION command selects
only distinct values.

SQL UNION ALL Example


Now we want to list all employees in Norway and USA:

SELECT E_Name FROM Employees_Norway


UNION ALL
SELECT E_Name FROM Employees_USA

34
Result

E_Name

Hansen, Ola

Svendson, Tove

Svendson, Stephen

Pettersen, Kari

Turner, Sally

Kent, Clark

Svendson, Stephen

Scott, Stephen

The SQL SELECT INTO Statement


 The SQL SELECT INTO statement can be used to create backup copies of tables.
 The SELECT INTO statement selects data from one table and inserts it into a different table.

 The SELECT INTO statement is most often used to create backup copies of tables.

 SQL SELECT INTO Syntax

We can select all columns into the new table:

SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename

Or we can select only the columns we want into the new table:

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename

35
SQL SELECT INTO Example
Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.

We use the following SQL statement:

SELECT *
INTO Persons_Backup
FROM Persons

We can also use the IN clause to copy the table into another database:

SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons

We can also copy only a few fields into the new table:

SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons

SQL SELECT INTO - With a WHERE Clause


We can also add a WHERE clause.

The following SQL statement creates a "Persons_Backup" table with only the persons who lives in the
city "Sandnes":

SELECT LastName,Firstname
INTO Persons_Backup
FROM Persons
WHERE City='Sandnes'

SQL SELECT INTO - Joined Tables


Selecting data from more than one table is also possible.

The following example creates a "Persons_Order_Backup" table contains data from the two tables
"Persons" and "Orders":

36
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id

The CREATE DATABASE Statement


 The CREATE DATABASE statement is used to create a database.

 SQL CREATE DATABASE Syntax:


CREATE DATABASE database_name

CREATE DATABASE Example


Now we want to create a database called "my_db".

We use the following CREATE DATABASE statement:

CREATE DATABASE my_db

Database tables can be added with the CREATE TABLE statement.

The CREATE TABLE Statement

The CREATE TABLE statement is used to create a table in a database.

SQL CREATE TABLE Syntax:


CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

The data type specifies what type of data the column can hold. For a complete reference of all the data
types available in MS Access, MySQL, and SQL Server.

CREATE TABLE Example


Now we want to create a table called "Persons" that contains five columns: P_Id, LastName, FirstName,
Address, and City.

We use the following CREATE TABLE statement:

37
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City
columns are of type varchar with a maximum length of 255 characters.

The empty "Persons" table will now look like this:

P_Id LastName FirstName Address City

The empty table can be filled with data with the INSERT INTO statement.

SQL Constraints
 Constraints are used to limit the type of data that can go into a table.
 Constraints can be specified when a table is created (with the CREATE TABLE statement) or
after the table is created (with the ALTER TABLE statement).

We will focus on the following constraints:

• NOT NULL
• UNIQUE

• PRIMARY KEY

• FOREIGN KEY

• CHECK

• DEFAULT

The next chapters will describe each constraint in details.

SQL NOT NULL Constraint


 The NOT NULL constraint enforces a column to NOT accept NULL values.
 The NOT NULL constraint enforces a field to always contain a value. This means that you cannot
insert a new record, or update a record without adding a value to this field.

38
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

SQL UNIQUE Constraint


 The UNIQUE constraint uniquely identifies each record in a database table.
 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
 Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:

MySQL:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

39
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns,
use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following
SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD UNIQUE (P_Id)

To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns,
use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

To DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


DROP INDEX uc_PersonID

SQL Server / Oracle / MS Access:

40
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID

SQL PRIMARY KEY Constraint


 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Primary keys must contain unique values.
 A primary key column cannot contain NULL values.
 Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:

MySQL:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

41
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the
following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).

To DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


DROP PRIMARY KEY

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY Constraint

42
 A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.

The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:

MySQL:

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

43
SQL Server / Oracle / MS Access:

CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

SQL FOREIGN KEY Constraint on ALTER TABLE


To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created,
use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint

44
To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Orders


DROP FOREIGN KEY fk_PerOrders

SQL Server / Oracle / MS Access:

ALTER TABLE Orders


DROP CONSTRAINT fk_PerOrders

SQL CHECK Constraint


 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for this
column.
 If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

SQL CHECK Constraint on CREATE TABLE


The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is
created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than
0.

My SQL:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

45
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)

SQL CHECK Constraint on ALTER TABLE


To create a CHECK constraint on the "P_Id" column when the table is already created, use the following
SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CHECK (P_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT chk_Person

SQL DEFAULT Constraint


 The DEFAULT constraint is used to insert a default value into a column.

46
 The default value will be added to all new records, if no other value is specified.

SQL DEFAULT Constraint on CREATE TABLE


The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is
created:

My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)

The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)

SQL DEFAULT Constraint on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:

MySQL:

ALTER TABLE Persons


ALTER City SET DEFAULT 'SANDNES'

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ALTER COLUMN City SET DEFAULT 'SANDNES'

To DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following SQL:

47
MySQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT

Indexes
 The CREATE INDEX statement is used to create indexes in tables.
 Indexes allow the database application to find data fast; without reading the whole table.
 An index can be created in a table to find data more quickly and efficiently.
 The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So you should only create indexes on columns (and tables) that will be frequently
searched against.

SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column_name)

SQL CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for
creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons"
table:

CREATE INDEX PIndex


ON Persons (LastName)

48
If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:

CREATE INDEX PIndex


ON Persons (LastName, FirstName)

The DROP INDEX Statement


 Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
 The DROP INDEX statement is used to delete an index in a table.

DROP INDEX Syntax for MS Access:


DROP INDEX index_name ON table_name

DROP INDEX Syntax for MS SQL Server:


DROP INDEX table_name.index_name

DROP INDEX Syntax for DB2/Oracle:


DROP INDEX index_name

DROP INDEX Syntax for MySQL:


ALTER TABLE table_name DROP INDEX index_name

The DROP TABLE Statement


The DROP TABLE statement is used to delete a table.

DROP TABLE table_name

The DROP DATABASE Statement


The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name

The TRUNCATE TABLE Statement


What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name

The ALTER TABLE Statement

49
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

SQL ALTER TABLE Syntax

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


ALTER COLUMN column_name datatype

SQL ALTER TABLE Example


Look at the "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ADD DateOfBirth date

Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types available in
MS Access, MySQL, and SQL Server, go to our complete Data Types reference.

The "Persons" table will now like this:

50
P_Id LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or
four-digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


DROP COLUMN DateOfBirth

The "Persons" table will now like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

AUTO INCREMENT a Field

51
 Auto-increment allows a unique number to be generated when a new record is inserted into a
table.
 Very often we would like the value of the primary key field to be created automatically every
time a new record is inserted.

We would like to create an auto-increment field in a table.

Syntax for MySQL

The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:

CREATE TABLE Persons


(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new
record.

To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:

ALTER TABLE Persons AUTO_INCREMENT=100

To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".

Syntax for SQL Server

The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:

CREATE TABLE Persons


(
P_Id int PRIMARY KEY IDENTITY,

52
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.

By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.

To specify that the "P_Id" column should start at value 10 and increment by 5, change the identity to
IDENTITY(10,5).

To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".

Syntax for Access

The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:

CREATE TABLE Persons


(
P_Id PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature.

By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new
record.

To specify that the "P_Id" column should start at value 10 and increment by 5, change the autoincrement
to AUTOINCREMENT(10,5).

To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):

53
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".

Syntax for Oracle

In Oracle the code is a little bit more tricky.

You will have to create an auto-increment field with the sequence object (this object generates a number
sequence).

Use the following CREATE SEQUENCE syntax:

CREATE SEQUENCE seq_person


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It
will also cache up to 10 values for performance. The cache option specifies how many sequence values
will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function
retrieves the next value from seq_person sequence):

INSERT INTO Persons (P_Id,FirstName,LastName)


VALUES (seq_person.nextval,'Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned the next number from the seq_person sequence. The "FirstName" column would be set to
"Lars" and the "LastName" column would be set to "Monsen".

SQL CREATE VIEW Statement


 In SQL, a view is a virtual table based on the result-set of an SQL statement.
 A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.

 You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.

 SQL CREATE VIEW Syntax:


CREATE VIEW view_name AS
SELECT column_name(s)

54
FROM table_name
WHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several views installed by default.

The view "Current Product List" lists all active products (products that are not discontinued) from the
"Products" table. The view is created with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

We can query the view above as follows:

SELECT * FROM [Current Product List]

Another view in the Northwind sample database selects every product in the "Products" table with a unit
price higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)

We can query the view above as follows:

SELECT * FROM [Products Above Average Price]

Another view in the Northwind database calculates the total sale for each category in 1997. Note that this
view selects its data from another view called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS


SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997]

We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":

55
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'

SQL Updating a View


You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax:


CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Now we want to add the "Category" column to the "Current Product List" view. We will update the view
with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No

SQL Dropping a View


You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax:


DROP VIEW view_name

SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to
insert, matches the format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected. However, if a
time portion is involved, it gets complicated.

Before talking about the complications of querying for dates, we will look at the most important built-in
functions for working with dates.

MySQL Date Functions


The following table lists the most important built-in date functions in MySQL:

56
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats

SQL Server Date Functions


The following table lists the most important built-in date functions in SQL Server:

Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats

SQL Date Data Types


MySQL comes with the following data types for storing a date or a date/time value in the database:

• DATE - format YYYY-MM-DD


• DATETIME - format: YYYY-MM-DD HH:MM:SS

• TIMESTAMP - format: YYYY-MM-DD HH:MM:SS

• YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in the database:

• DATE - format YYYY-MM-DD


• DATETIME - format: YYYY-MM-DD HH:MM:SS

• SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS

• TIMESTAMP - format: a unique number

57
Note: The date types are chosen for a column when you create a new table in your database!

For an overview of all data types available.

SQL Working with Dates


You can compare two dates easily if there is no time component involved!

Assume we have the following "Orders" table:

OrderId ProductName OrderDate


1 Geitost 2008-11-11
2 Camembert Pierrot 2008-11-09
3 Mozzarella di Giovanni 2008-11-11
4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId ProductName OrderDate


1 Geitost 2008-11-11
3 Mozzarella di Giovanni 2008-11-11

Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):

OrderId ProductName OrderDate


1 Geitost 2008-11-11 13:23:44
2 Camembert Pierrot 2008-11-09 15:45:21
3 Mozzarella di Giovanni 2008-11-11 11:12:01
4 Mascarpone Fabioli 2008-10-29 14:56:59

If we use the same SELECT statement as above:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

we will get no result! This is because the query is looking only for dates with no time portion.

58
Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your
dates!

Definition and Usage

NOW() returns the current date and time.

Syntax
NOW()

Example

The following SELECT statement:

SELECT NOW(),CURDATE(),CURTIME()

will result in something like this:

NOW() CURDATE() CURTIME()

2008-11-11 12:45:34 2008-11-11 12:45:34

Example

The following SQL creates an "Orders" table with a datetime column (OrderDate):

CREATE TABLE Orders


(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (OrderId)
)

Notice that the OrderDate column specifies NOW() as the default value. As a result, when you insert a
row into the table, the current date and time are automatically inserted into the column.

Now we want to insert a record into the "Orders" table:

INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')

The "Orders" table will now look something like this:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

59
Definition and Usage

CURDATE() returns the current date.

Syntax
CURDATE()

Example

The following SELECT statement:

SELECT NOW(),CURDATE(),CURTIME()

will result in something like this:

NOW() CURDATE() CURTIME()

2008-11-11 12:45:34 2008-11-11 12:45:34

Example

The following SQL creates an "Orders" table with a datetime column (OrderDate):

CREATE TABLE Orders


(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (OrderId)
)

Notice that the OrderDate column specifies CURDATE() as the default value. As a result, when you insert
a row into the table, the current date are automatically inserted into the column.

Now we want to insert a record into the "Orders" table:

INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')

The "Orders" table will now look something like this:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11

60
Definition and Usage

CURTIME() returns the current time.

Syntax
CURTIME()

Example

The following SELECT statement:

SELECT NOW(),CURDATE(),CURTIME()

will result in something like this:

NOW() CURDATE() CURTIME()

2008-11-11 12:45:34 2008-11-11 12:45:34

Definition and Usage

The DATE() function extracts the date part of a date or date/time expression.

Syntax
DATE(date)

Where date is a valid date expression.

Example

Assume we have the following "Orders" table:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

The following SELECT statement:

SELECT ProductName, DATE(OrderDate) AS OrderDate


FROM Orders
WHERE OrderId=1

will result in this:

61
ProductName OrderDate

Jarlsberg Cheese 2008-11-11

Definition and Usage

The EXTRACT() function is used to return a single part of a date/time, such as year, month, day, hour,
minute, etc.

Syntax
EXTRACT(unit FROM date)

Where date is a valid date expression and unit can be one of the following:

Unit Value

MICROSECOND

SECOND

MINUTE

HOUR

DAY

WEEK

MONTH

QUARTER

YEAR

SECOND_MICROSECOND

MINUTE_MICROSECOND

MINUTE_SECOND

HOUR_MICROSECOND

HOUR_SECOND

62
HOUR_MINUTE

DAY_MICROSECOND

DAY_SECOND

DAY_MINUTE

DAY_HOUR

YEAR_MONTH

Example

Assume we have the following "Orders" table:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

The following SELECT statement:

SELECT EXTRACT(YEAR FROM OrderDate) AS OrderYear,


EXTRACT(MONTH FROM OrderDate) AS OrderMonth,
EXTRACT(DAY FROM OrderDate) AS OrderDay,
FROM Orders
WHERE OrderId=1

will result in this:

OrderYear OrderMonth OrderDay

2008 11 11

Definition and Usage

The DATE_ADD() function adds a specified time interval to a date.

Syntax
DATE_ADD(date,INTERVAL expr type)

Where date is a valid date expression and expr is the number of interval you want to add.

type can be one of the following:

63
Type Value

MICROSECOND

SECOND

MINUTE

HOUR

DAY

WEEK

MONTH

QUARTER

YEAR

SECOND_MICROSECOND

MINUTE_MICROSECOND

MINUTE_SECOND

HOUR_MICROSECOND

HOUR_SECOND

HOUR_MINUTE

DAY_MICROSECOND

DAY_SECOND

DAY_MINUTE

DAY_HOUR

YEAR_MONTH

Example

Assume we have the following "Orders" table:

64
OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

Now we want to add 45 days to the "OrderDate", to find the payment date.

We use the following SELECT statement:

SELECT OrderId,DATE_ADD(OrderDate,INTERVAL 45 DAY) AS OrderPayDate


FROM Orders

Result:

OrderId OrderPayDate

1 2008-12-26 13:23:44.657

Definition and Usage

The DATE_SUB() function subtracts a specified time interval from a date.

Syntax
DATE_SUB(date,INTERVAL expr type)

Where date is a valid date expression and expr is the number of interval you want to subtract.

type can be one of the following:

Type Value

MICROSECOND

SECOND

MINUTE

HOUR

DAY

WEEK

MONTH

65
QUARTER

YEAR

SECOND_MICROSECOND

MINUTE_MICROSECOND

MINUTE_SECOND

HOUR_MICROSECOND

HOUR_SECOND

HOUR_MINUTE

DAY_MICROSECOND

DAY_SECOND

DAY_MINUTE

DAY_HOUR

YEAR_MONTH

Example

Assume we have the following "Orders" table:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

Now we want to subtract 5 days from the "OrderDate" date.

We use the following SELECT statement:

SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 5 DAY) AS SubtractDate


FROM Orders

Result:

66
OrderId SubtractDate

1 2008-11-06 13:23:44.657

Definition and Usage

The DATEDIFF() function returns the time between two dates.

Syntax
DATEDIFF(date1,date2)

Where date1 and date2 are valid date or date/time expressions.

Note: Only the date parts of the values are used in the calculation.

Example

The following SELECT statement:

SELECT DATEDIFF('2008-11-30','2008-11-29') AS DiffDate

will result in this:

DiffDate

Example

The following SELECT statement:

SELECT DATEDIFF('2008-11-29','2008-11-30') AS DiffDate

will result in this:

DiffDate

-1

Definition and Usage

67
The DATE_FORMAT() function is used to display date/time data in different formats.

Syntax
DATE_FORMAT(date,format)

Where date is a valid date and format specifies the output format for the date/time.

The formats that can be used are:

Format Description

%a Abbreviated weekday name

%b Abbreviated month name

%c Month, numeric

%D Day of month with English suffix

%d Day of month, numeric (00-31)

%e Day of month, numeric (0-31)

%f Microseconds

%H Hour (00-23)

%h Hour (01-12)

%I Hour (01-12)

%i Minutes, numeric (00-59)

%j Day of year (001-366)

%k Hour (0-23)

%l Hour (1-12)

%M Month name

%m Month, numeric (00-12)

%p AM or PM

%r Time, 12-hour (hh:mm:ss AM or PM)

68
%S Seconds (00-59)

%s Seconds (00-59)

%T Time, 24-hour (hh:mm:ss)

%U Week (00-53) where Sunday is the first day of week

%u Week (00-53) where Monday is the first day of week

%V Week (01-53) where Sunday is the first day of week, used with %X

%v Week (01-53) where Monday is the first day of week, used with %x

%W Weekday name

%w Day of the week (0=Sunday, 6=Saturday)

%X Year of the week where Sunday is the first day of week, four digits, used with %V

%x Year of the week where Monday is the first day of week, four digits, used with %v

%Y Year, four digits

%y Year, two digits

Example

The following script uses the DATE_FORMAT() function to display different formats. We will use the
NOW() function to get the current date/time:

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')


DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')

The result would look something like this:

Nov 04 2008 11:45 PM


11-04-2008
04 Nov 08
04 Nov 2008 11:45:34:243

Definition and Usage

69
The GETDATE() function returns the current date and time from the SQL Server.

Syntax
GETDATE()

Example

The following SELECT statement:

SELECT GETDATE() AS CurrentDateTime

will result in something like this:

CurrentDateTime

2008-11-11 12:45:34.243

Note: The time part above goes all the way to milliseconds.

Example

The following SQL creates an "Orders" table with a datetime column (OrderDate):

CREATE TABLE Orders


(
OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)

Notice that the OrderDate column specifies GETDATE() as the default value. As a result, when you insert
a row into the table, the current date and time are automatically inserted into the column.

Now we want to insert a record into the "Orders" table:

INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')

The "Orders" table will now look something like this:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

70
Definition and Usage

The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour,
minute, etc.

Syntax
DATEPART(datepart,date)

Where date is a valid date expression and datepart can be one of the following:

datepart Abbreviation

year yy, yyyy

quarter qq, q

month mm, m

dayofyear dy, y

day dd, d

week wk, ww

weekday dw, w

hour hh

minute mi, n

second ss, s

millisecond ms

microsecond mcs

nanosecond ns

Example

Assume we have the following "Orders" table:

71
OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

The following SELECT statement:

SELECT DATEPART(yyyy,OrderDate) AS OrderYear,


DATEPART(mm,OrderDate) AS OrderMonth,
DATEPART(dd,OrderDate) AS OrderDay,
FROM Orders
WHERE OrderId=1

will result in this:

OrderYear OrderMonth OrderDay

2008 11 11

Definition and Usage

The DATEADD() function is adds or subtracts a specified time interval from a date.

Syntax
DATEADD(datepart,number,date)

Where date is a valid date expression and number is the number of interval you want to add. The number
can either be positive, for dates in the future, or negative, for dates in the past.

datepart can be one of the following:

datepart Abbreviation

year yy, yyyy

quarter qq, q

month mm, m

dayofyear dy, y

day dd, d

week wk, ww

72
weekday dw, w

hour hh

minute mi, n

second ss, s

millisecond ms

microsecond mcs

nanosecond ns

Example

Assume we have the following "Orders" table:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2008-11-11 13:23:44.657

Now we want to add 45 days to the "OrderDate", to find the payment date.

We use the following SELECT statement:

SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate


FROM Orders

Result:

OrderId OrderPayDate

1 2008-12-26 13:23:44.657

Definition and Usage

The DATEDIFF() function returns the time between two dates.

Syntax
DATEDIFF(datepart,startdate,enddate)

73
Where startdate and enddate are valid date expressions and datepart can be one of the following:

datepart Abbreviation

year yy, yyyy

quarter qq, q

month mm, m

dayofyear dy, y

day dd, d

week wk, ww

weekday dw, w

hour hh

minute mi, n

second ss, s

millisecond ms

microsecond mcs

nanosecond ns

Example

Now we want to get the number of days between two dates.

We use the following SELECT statement:

SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate

Result:

DiffDate

61

74
Example

Now we want to get the number of days between two dates (notice that the second date is "earlier" than
the first date, and will result in a negative number).

We use the following SELECT statement:

SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate

Result:

DiffDate

-61

Definition and Usage

The CONVERT() function is a general function for converting data into a new data type.

The CONVERT() function can be used to display date/time data in different formats.

Syntax
CONVERT(data_type(length),data_to_be_converted,style)

Where data_type(length) specifies the target data type (with an optional length), data_to_be_converted
contains the value to be converted, and style specifies the output format for the date/time.

The styles that can be used are:

Style ID Style Format

100 or 0 mon dd yyyy hh:miAM (or PM)

101 mm/dd/yy

102 yy.mm.dd

103 dd/mm/yy

104 dd.mm.yy

105 dd-mm-yy

75
106 dd mon yy

107 Mon dd, yy

108 hh:mm:ss

109 or 9 mon dd yyyy hh:mi:ss:mmmAM (or PM)

110 mm-dd-yy

111 yy/mm/dd

112 yymmdd

113 or 13 dd mon yyyy hh:mm:ss:mmm(24h)

114 hh:mi:ss:mmm(24h)

120 or 20 yyyy-mm-dd hh:mi:ss(24h)

121 or 21 yyyy-mm-dd hh:mi:ss.mmm(24h)

126 yyyy-mm-ddThh:mm:ss.mmm(no spaces)

130 dd mon yyyy hh:mi:ss:mmmAM

131 dd/mm/yy hh:mi:ss:mmmAM

Example

The following script uses the CONVERT() function to display different formats. We will use the
GETDATE() function to get the current date/time:

CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)

The result would look something like this:

Nov 04 2008 11:45 PM


11-04-2008
04 Nov 08
04 Nov 2008 11:45:34:243

76
NULL values represent missing unknown data. By default, a table column can hold NULL values.

SQL NULL Values


 If a column in a table is optional, we can insert a new record or update an existing record without
adding a value to this column. This means that the field will be saved with a NULL value.
 NULL values are treated differently from other values.
 NULL is used as a placeholder for unknown or inapplicable values.
 Note: It is not possible to compare NULL and 0; they are not equivalent.

SQL Working with NULL Values


Look at the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Stavanger

Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a
record with no value for the "Address" column, the "Address" column will be saved with a NULL value.

How can we test for NULL values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

SQL IS NULL
How do we select only the records with NULL values in the "Address" column?

We will have to use the IS NULL operator:

SELECT LastName,FirstName,Address FROM Persons


WHERE Address IS NULL

The result-set will look like this:

LastName FirstName Address


Hansen Ola
Pettersen Kari

Tip: Always use IS NULL to look for NULL values.

77
SQL IS NOT NULL
How do we select only the records with no NULL values in the "Address" column?

We will have to use the IS NOT NULL operator:

SELECT LastName,FirstName,Address FROM Persons


WHERE Address IS NOT NULL

The result-set will look like this:

LastName FirstName Address


Svendson Tove Borgvn 23

In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.

SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions

Look at the following "Products" table:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder


1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.

We have the following SELECT statement:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products

In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL.

Microsoft's ISNULL() function is used to specify how we want to treat NULL values.

The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.

In this case we want NULL values to be zero.

Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if
the value is NULL:

SQL Server / MS Access

78
SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products

Oracle

Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the
same result:

SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products

MySQL

MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's
ISNULL() function.

In MySQL we can use the IFNULL() function, like this:

SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products

or we can use the COALESCE() function, like this:

SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products

Microsoft Access Data Types


Data types and ranges for Microsoft Access, MySQL and SQL Server.

Data type Description Storage


Text Use for text or combinations of text and numbers. 255 characters
maximum
Memo Memo is used for larger amounts of text. Stores up to 65,536
characters. Note: You cannot sort a memo field. However, they are
searchable
Byte Allows whole numbers from 0 to 255 1 byte
Integer Allows whole numbers between -32,768 and 32,767 2 bytes
Long Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Single Single precision floating-point. Will handle most decimals 4 bytes
Double Double precision floating-point. Will handle most decimals 8 bytes
Currency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal 8 bytes
places. Tip: You can choose which country's currency to use
AutoNumber AutoNumber fields automatically give each record its own number, 4 bytes
usually starting at 1

79
Date/Time Use for dates and times 8 bytes
Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In code, 1 bit
use the constants True and False (equivalent to -1 and 0).Note: Null values
are not allowed in Yes/No fields
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) up to 1GB
Hyperlink Contain links to other files, including web pages
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down 4 bytes
list

MySQL Data Types


In MySQL there are three main types : text, number, and Date/Time types.

Text types:

Data type Description


CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The
fixed size is specified in parenthesis. Can store up to 255 characters
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The
maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you
put a greater value than 255 it will be converted to a TEXT type
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list.
If a value is inserted that is not in the list, a blank value will be inserted.

Note: The values are sorted in the order you enter them.

You enter the possible values in this format: ENUM('X','Y','Z')


SET Similar to ENUM except that SET may contain up to 64 list items and can store more
than one choice

Number types:

Data type Description


TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be

80
specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
MEDIUMINT(size -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number
) of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may
be specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of
digits to the right of the decimal point is specified in the d parameter

*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative
to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a
negative number.

Date types:

Data type Description


DATE() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix
epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07'
UTC
TIME() A time. Format: HH:MM:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR() A year in two-digit or four-digit format.
Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit
format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.

81
TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS,
YYYYMMDD, or YYMMDD.

SQL Server Data Types


Character strings:

Data type Description Storage


char(n) Fixed-length character string. Maximum 8,000 characters n
varchar(n) Variable-length character string. Maximum 8,000 characters
varchar(max) Variable-length character string. Maximum 1,073,741,824 characters
text Variable-length character string. Maximum 2GB of text data

Unicode strings:

Data type Description Storage


nchar(n) Fixed-length Unicode data. Maximum 4,000 characters
nvarchar(n) Variable-length Unicode data. Maximum 4,000 characters
nvarchar(max) Variable-length Unicode data. Maximum 536,870,912 characters
ntext Variable-length Unicode data. Maximum 2GB of text data

Binary types:

Data type Description Storage


bit Allows 0, 1, or NULL
binary(n) Fixed-length binary data. Maximum 8,000 bytes
varbinary(n) Variable-length binary data. Maximum 8,000 bytes
varbinary(max) Variable-length binary data. Maximum 2GB
image Variable-length binary data. Maximum 2GB

Number types:

Data type Description Storage


tinyint Allows whole numbers from 0 to 255 1 byte
smallint Allows whole numbers between -32,768 and 32,767 2 bytes

82
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes
9,223,372,036,854,775,807
decimal(p,s) Fixed precision and scale numbers. 5-17 bytes

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the
decimal point. s must be a value from 0 to p. Default value is 0
numeric(p,s Fixed precision and scale numbers. 5-17 bytes
)
Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the
decimal point. s must be a value from 0 to p. Default value is 0
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) bytes
holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date types:

Data type Description Storage


datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8 bytes
nanoseconds
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes
timestamp Stores a unique number that gets updated every time a row gets created or

83
modified. The timestamp value is based upon an internal clock and does not
correspond to real time. Each table may have only one timestamp variable

Other data types:

Data type Description


sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML formatted data. Maximum 2GB
cursor Stores a reference to a cursor used for database operations
table Stores a result-set for later processing

SQL FUNCTIONS

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

• AVG() - Returns the average value


• COUNT() - Returns the number of rows

• FIRST() - Returns the first value

• LAST() - Returns the last value

• MAX() - Returns the largest value

• MIN() - Returns the smallest value

• SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value.

Useful scalar functions:

• UCASE() - Converts a field to upper case


• LCASE() - Converts a field to lower case

84
• MID() - Extract characters from a text field

• LEN() - Returns the length of a text field

• ROUND() - Rounds a numeric field to the number of decimals specified

• NOW() - Returns the current system date and time

• FORMAT() - Formats how a field is to be displayed

The AVG() Function


The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax


SELECT AVG(column_name) FROM table_name

SQL AVG() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to find the average value of the "OrderPrice" fields.

We use the following SQL statement:

SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

The result-set will look like this:

85
OrderAverage

950

Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice
value.

We use the following SQL statement:

SELECT Customer FROM Orders


WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

The result-set will look like this:

Customer

Hansen

Nilsen

Jensen

SQL COUNT
The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:

SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified
column:

SELECT COUNT(DISTINCT column_name) FROM table_name

86
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.

SQL COUNT(column_name) Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to count the number of orders from "Customer Nilsen".

We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerNilsen FROM Orders


WHERE Customer='Nilsen'

The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:

CustomerNilsen

SQL COUNT(*) Example


If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders

The result-set will look like this:

NumberOfOrders

87
6

which is the total number of rows in the table.

SQL COUNT(DISTINCT column_name) Example


Now we want to count the number of unique customers in the "Orders" table.

We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders

The result-set will look like this:

NumberOfCustomers

which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.

The FIRST() Function


The FIRST() function returns the first value of the selected column.

SQL FIRST() Syntax


SELECT FIRST(column_name) FROM table_name

SQL FIRST() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

88
Now we want to find the first value of the "OrderPrice" column.

We use the following SQL statement:

SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders

Tip: Workaround if FIRST() function is not supported:

SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1

The result-set will look like this:

FirstOrderPrice

1000

The LAST() Function


The LAST() function returns the last value of the selected column.

SQL LAST() Syntax


SELECT LAST(column_name) FROM table_name

SQL LAST() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

89
Now we want to find the last value of the "OrderPrice" column.

We use the following SQL statement:

SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders

Tip: Workaround if LAST() function is not supported:

SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1

The result-set will look like this:

LastOrderPrice

100

The MAX() Function


The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax


SELECT MAX(column_name) FROM table_name

SQL MAX() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to find the largest value of the "OrderPrice" column.

We use the following SQL statement:

90
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders

The result-set will look like this:

LargestOrderPrice

2000

The MIN() Function


The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax


SELECT MIN(column_name) FROM table_name

SQL MIN() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to find the smallest value of the "OrderPrice" column.

We use the following SQL statement:

SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders

The result-set will look like this:

SmallestOrderPrice

100

91
The SUM() Function
The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax


SELECT SUM(column_name) FROM table_name

SQL SUM() Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to find the sum of all "OrderPrice" fields".

We use the following SQL statement:

SELECT SUM(OrderPrice) AS OrderTotal FROM Orders

The result-set will look like this:

OrderTotal

5700

Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement

92
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by
one or more columns.

SQL GROUP BY Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name

SQL GROUP BY Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Now we want to find the total sum (total order) of each customer.

We will have to use the GROUP BY statement to group the customers.

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders


GROUP BY Customer

The result-set will look like this:

Customer SUM(OrderPrice)

Hansen 2000

Nilsen 1700

Jensen 2000

93
Nice! Isn't it? :)

Let's see what happens if we omit the GROUP BY statement:

SELECT Customer,SUM(OrderPrice) FROM Orders

The result-set will look like this:

Customer SUM(OrderPrice)

Hansen 5700

Nilsen 5700

Hansen 5700

Hansen 5700

Jensen 5700

Nilsen 5700

The result-set above is not what we wanted.

Explanation of why the above SELECT statement cannot be used: The SELECT statement above has
two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value
(that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each
row in the "Orders" table). This will therefore not give us the correct result. However, you have seen that
the GROUP BY statement solves this problem.

GROUP BY More Than One Column


We can also use the GROUP BY statement on more than one column, like this:

SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders


GROUP BY Customer,OrderDate

The UCASE() Function


The UCASE() function converts the value of a field to uppercase.

SQL UCASE() Syntax


SELECT UCASE(column_name) FROM table_name

Syntax for SQL Server


SELECT UPPER(column_name) FROM table_name

94
SQL UCASE() Example
We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the
"LastName" column to uppercase.

We use the following SELECT statement:

SELECT UCASE(LastName) as LastName,FirstName FROM Persons

The result-set will look like this:

LastName FirstName

HANSEN Ola

SVENDSON Tove

PETTERSEN Kari

The LCASE() Function


The LCASE() function converts the value of a field to lowercase.

SQL LCASE() Syntax


SELECT LCASE(column_name) FROM table_name

Syntax for SQL Server


SELECT LOWER(column_name) FROM table_name

SQL LCASE() Example


We have the following "Persons" table:

P_Id LastName FirstName Address City

95
1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the
"LastName" column to lowercase.

We use the following SELECT statement:

SELECT LCASE(LastName) as LastName,FirstName FROM Persons

The result-set will look like this:

LastName FirstName

hansen Ola

svendson Tove

pettersen Kari

The MID() Function


The MID() function is used to extract characters from a text field.

SQL MID() Syntax


SELECT MID(column_name,start[,length]) FROM table_name

Parameter Description

column_nam Required. The field to extract characters from


e

start Required. Specifies the starting position (starts at 1)

length Optional. The number of characters to return. If omitted, the MID() function returns the rest
of the text

96
SQL MID() Example
We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to extract the first four characters of the "City" column above.

We use the following SELECT statement:

SELECT MID(City,1,4) as SmallCity FROM Persons

The result-set will look like this:

SmallCity

Sand

Sand

Stav

The LEN() Function


The LEN() function returns the length of the value in a text field.

SQL LEN() Syntax


SELECT LEN(column_name) FROM table_name

SQL LEN() Example


We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

97
2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the length of the values in the "Address" column above.

We use the following SELECT statement:

SELECT LEN(Address) as LengthOfAddress FROM Persons

The result-set will look like this:

LengthOfAddress

12

The ROUND() Function


The ROUND() function is used to round a numeric field to the number of decimals specified.

SQL ROUND() Syntax

SELECT ROUND(column_name,decimals) FROM table_name

Parameter Description

column_name Required. The field to round.

decimals Required. Specifies the number of decimals to be returned.

SQL ROUND() Example

98
We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 15.67

Now we want to display the product name and the price rounded to the nearest integer.

We use the following SELECT statement:

SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products

The result-set will look like this:

ProductName UnitPrice

Jarlsberg 10

Mascarpone 33

Gorgonzola 16

The NOW() Function


The NOW() function returns the current system date and time.

SQL NOW() Syntax


SELECT NOW() FROM table_name

SQL NOW() Example


We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 15.67

99
Now we want to display the products and prices per today's date.

We use the following SELECT statement:

SELECT ProductName, UnitPrice, Now() as PerDate FROM Products

The result-set will look like this:

ProductName UnitPrice PerDate

Jarlsberg 10.45 10/7/2008 11:25:02 AM

Mascarpone 32.56 10/7/2008 11:25:02 AM

Gorgonzola 15.67 10/7/2008 11:25:02 AM

The FORMAT() Function


The FORMAT() function is used to format how a field is to be displayed.

SQL FORMAT() Syntax


SELECT FORMAT(column_name,format) FROM table_name

Parameter Description

column_name Required. The field to be formatted.

format Required. Specifies the format.

SQL FORMAT() Example


We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice

1 Jarlsberg 1000 g 10.45

2 Mascarpone 1000 g 32.56

3 Gorgonzola 1000 g 15.67

100
Now we want to display the products and prices per today's date (with today's date displayed in the
following format "YYYY-MM-DD").

We use the following SELECT statement:

SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate


FROM Products

The result-set will look like this:

ProductName UnitPrice PerDate

Jarlsberg 10.45 2008-10-07

Mascarpone 32.56 2008-10-07

Gorgonzola 15.67 2008-10-07

101
SQL COMMANDS

Prepared By
Pandeeswari M
CONTENTS

1.FUNDAMENTALS OF SQL
2.FILTERING COMMANDS
3.ORDERING COMMANDS
4.ALIAS
5.AGGREGATE COMMANDS
6.GROUP BY COMMANDS
7.CONDITIONAL STATEMENT
8.JOINS
9.SUBQUERY
10.VIEW & INDEX
11.STRING FUNCTIONS
12.MATHEMATICAL FUNCTIONS
13. DATE-TIME FUNCTIONS
14.PATTERN MATCHING(regex)
15.DATA TYPE CONVERSION FUNCTIONS
DQL(Data Query Language)
To fetch the data from the database
Example: SELECT

DML(Data Manipulation Language)-


To modify the database objects
Example: INSERT,UPDATE,DELETE

DDL(Data Definition Language)


To create & modify database objects
Example: CREATE,DROP,ALTER,TRUNCATE
1.Fundamentals of SQL

CREATE

CREATE statement is used to create a table

Syntax:
CREATE TABLE ‘’TABLE_NAME’’(
‘’COLUMN1’’ ‘’DATA_TYPE’’ CONSTRAINTS,
‘’COLUMN2’’ ‘’DATA_TYPE’’ CONSTRAINTS,
‘’COLUMN3’’ ‘’DATA_TYPE’’ CONSTRAINTS,
………………………………………………………………..
‘’COLUMN N’’ ‘’DATA_TYPE’’ CONSTRAINTS
);

INSERT

INSERT statement is used insert new data


into the table
Syntax:
INSERT INTO
“TABLE_NAME” (COL1, COL2, ……..COL_N)
VALUES (Col_val_1,Col_val_2, ……. Col_val_N);

Import data from file(PostgreSQL)


For csv file
COPY TABLE_NAME(column1, column2,… ) FROM
FILE_PATH DELIMITER ‘ , ’ CSV HEADER;

For txt file


COPY TABLE_NAME(column1, column2,… ) FROM
FILE_PATH DELIMITER ‘ , ’ ;

SELECT

SELECT statement is used to retrieve data from


the table

Syntax
SELECT * FROM “TABLE_NAME”;
For select one column
SELECT “COLUMN_NAME” FROM “TABLE_NAME”;
For select multiple columns
SELECT “COLUMN1,COLUMN2,…”
FROM “TABLE_NAME”;
For select all columns
SELECT * FROM “TABLE_NAME”;

DISTINCT

DISTINCT keyword is used to eliminate all


duplicate records & fetch only unique records

Syntax:
SELECT DISTINCT(*) FROM “TABLE_NAME”;

WHERE

WHERE clause is used to filter a records

Syntax:
SELECT “COLUMN_NAME(S)”
FROM “TABLE_NAME “
WHERE CONDITION;

AND/OR
The AND/OR is used to combine multiple conditions

Syntax:
SELECT “COLUMN_NAMES(s)”
FROM “TABLE_NAME”
WHERE CONDITION AND/OR CONDITION;

UPDATE

It is used to modify the existing data in the


table

Syntax:
UPDATE “TABLE_NAME”
SET COL_1=VAL_1,COL_2=VAL_2,…
WHERE CONDITION;

DELETE

It is used to delete existing records in the table


Syntax:
For delete all rows
DELETE FROM “TABLE_NAME”;
For delete single/multiple row(s)
DELETE FROM “TABLE_NAME “
WHERE CONDITION;

ALTER

It is used to change the definition or structure


of the table

Syntax:
ADD COLUMN
ALTER TABLE “ TABLE_NAME”
ADD “COLUMN_NAME “ “DATA_TYPE”;
DROP COLUMN
ALETR TABLE “TABLE_NAME”
DROP “COLUMN_NAME”;
MODIFY DATA TYPE
ALTER TABLE “TABLE_NAME”
ALTER COLUMN “COL_NAME” TYPE NEW_DATA_TYPE;
RENAME COLUMN
ALTER TABLE “TABLE_NAME”
RENAME COLUMN “COL_NAME” TO “NEW_NAME”;
ADD CONSTRAINTS
ALTER TABLE “TABLE_NAME”
ADD CONSTRAINT COL_NAME CHECK CONDITION;

2.Filtering Commands

IN

Used to reduce multiple OR logical operator in


SELECT,DELETE,INSERT & UPDATE statements

Syntax:
SELECT “COL_NAME” FROM “TABLE_NAME”
WHERE “COL_NAME” IN (‘VAL1’, ’VAL2’,…);

BETWEEN

Used to retrieve data within a given range


Syntax:
SELECT “COL_NAME(S)” FROM “TABLE_NAME”
WHERE “COL_NAME” BETWEEN “VAL1” AND “VAL2”;

LIKE

Used to perform pattern matching/regex using


wildcards(% , _)
% - match any string of any length
_ - match on a single character

Syntax:
SELECT “COL_NAME” FROM “TABLE_NAME”
WHERE “COL_NAME” LIKE ‘PATTERN’;

3.Ordering Commands

ORDER BY

Used to sort the data & it is only used in


SELECT statement
Syntax:
SELECT “COL_NAME(s)” FROM “TABLE_NAME”
ORDER BY “COL_NAME” ASC/DESC;

LIMIT

Used to limit the number of records based on a


given limit

Syntax:
SELECT “COL_NAME(S)” FROM “TABLE_NAME”
[WHERE & ORDER BY – Optional]
LIMIT “LIMIT_VALUE”;

4.ALIAS
AS

Used to assign an alias to the column


Syntax:
SELECT “COL_NAME” as “COL_ALIAS”
FROM “TABLE_NAME”;

5.AGGREGATE COMMANDS

COUNT

Used to count the expression

Syntax:
SELECT COUNT(COL_NAME) FROM “TABLE_NAME”;

SUM

Used to sum the expression

Syntax:
SELECT SUM(COL_NAME) FROM “TABLE_NAME”;
AVG

Used to average the expression

Syntax:
SELECT AVG(COL_NAME) FROM “TABLE_NAME”;

MIN

Used to retrieve the minimum value

Syntax:
SELECT MIN(COL_NAME) FROM “TABLE_NAME”;

MAX

Used to retrieve the maximum value

Syntax:
SELECT MAX(COL_NAME) FROM “TABLE_NAME”;
6.GROUP BY COMMANDS

GROUP BY

GROUP BY clause is used to group the results by


one or more columns

Syntax:
SELECT “COL_1”, “COL_2”,…… FROM “TABLE_NAME”
GROUP BY “COL_NAME”;

HAVING

HAVING clause is added to SQL because the


WHERE keyword cannot be used with aggregate
functions

Syntax:
SELECT “COL_1”, “COL_2”,…… FROM “TABLE_NAME”
GROUP BY “COL_NAME”
HAVING ‘CONDITION’;
7.CONDITIONAL STATEMENT

CASE

CASE expression is a conditional expression

Syntax:
CASE
WHEN CONDITION THEN RESULT
[WHEN CONDITION THEN RESULT]
[WHEN CONDITION THEN RESULT]
ELSE RESULT
END

8.JOINS
JOINS used to fetch data from multiple tables
TYPES:

INNER JOIN

INNER JOIN produces only the set of records


that match in table A and table B
Syntax:
SELECT COL1,COL2,…..
FROM “TABLE_1”
INNER JOIN “TABLE_2”
ON TABLE_1. COMMON_COL = TABLE_2. COMMON_COL;

LEFT JOIN

LEFT JOIN returns all the rows in the table


A(Left),even if there is no matches in the table B(Right)

Syntax:
SELECT COL_1,COL_2,…
FROM “TABLE_1”
LEFT JOIN “TABLE_2”
ON TABLE_1. COMMON_COL = TABLE_2. COMMON_COL;

RIGHT JOIN

RIGHT JOIN returns all the rows in the


table B(Right),even if there is no matches in the table
A(left)
Syntax:
SELECT COL_1,COL_2,…
FROM “TABLE_1”
RIGHT JOIN “TABLE_2”
ON TABLE_1.COMMON_COL = TABLE_2. COMMON_COL;

FULL JOIN

FULL JOIN combines the results of both


right & left join

Syntax:
SELECT COL_1,COL_2,…
FROM “TABLE_1”
FULL JOIN “TABLE_2”
ON TABLE_1.COMMON_COL = TABLE_2. COMMON_COL;

CROSS JOIN

CROSS JOIN creates Cartesian product


between two sets

Syntax:
SELECT TAB1.COL,TAB2.COL,…..
FROM “TABLE_1”, “TABLE_2”,……..

EXCEPT

Used to fetch all the data from table A except that


matches with table B

Syntax:
SELECT COL1,COL2,……..
FROM TABLE_A [WHERE]
EXCEPT
SELECT COL_1,COL_2,……
FROM TABLE_B [WHERE];

UNION

Used to combine two or more SELECT statements

Syntax:
SELECT COL1,COL2,……..
FROM TABLE_A [WHERE]
UNION
SELECT COL_1,COL_2,……
FROM TABLE_B [WHERE];
SUBQUERY

SUBQUERY is a query within a query


Syntax:
SUBQUERY is in WHERE clause
SELECT “COL_1” FROM “TABLE_NAME_1”
WHERE “COL_2” [operator]
(SELECT “COL_3” FROM “TABLE_NAME_2”
WHERE CONDITION);

VIEW

VIEW is a virtual table created by a query


joining one or more tables
Syntax:
CREATE[OR RESPONSE] view_name AS
SELECT “COL_NAME(S)”
FROM “TABLE_NAME”

INDEX
An INDEX creates an entry for each value that
appears in the indexed column
Syntax:
CREATE[UNIQUE] INDEX “index_name”
ON “TABLE_NAME”
(index_col1 [ASC/DESC],………..

11.STRING FUNCTIONS

LENGTH:

LENGTH function retrieves the length of the


specified string
Syntax:
LENGTH(‘string’)

UPPER/LOWER

UPPER/LOWER function converts all the


characters in the specified string to
uppercase/lowercase
Syntax:
upper(‘string’)
lower(‘string’)

REPLACE

REPLACE function replaces all the


occurrences of the specified string
Syntax:
REPLACE(‘string’, ’from string’, to string’)

TRIM

TRIM function removes all specified characters


either from beginning or end of the string or both
Syntax:
TRIM( [Leading|Trailing|Both] [trim char] from string)

RTRIM

RTRIM function removes all specified characters


from RHS of the string
Syntax:
RTRIM(‘string’, trim char)

LTRIM
LTRIM function removes all specified characters
from LHS of the string

Syntax:
LTRIM(‘string’, trim char)

CONCATENATION

|| operator used to concatenate two or more


strings
Syntax:
‘string_1’ || ‘string_2’ || ‘string_3’

SUBSTRING

SUBSTRING function used to extract substring


from a string
Syntax:
SUBSTRING(‘string’ [start position]
[substring length]);

STRING_AGG
String aggregate function concatenates input
values into a string, separated by a delimiter

Syntax
STRING_AGG(‘expression’, delimiter)

12.MATHEMATICAL FUNCTIONS

CEIL

CEIL function returns the smallest integer value


which is greater than or equal to a number
Syntax:
CEIL(number)

FLOOR

FLOOR function returns the largest integer value


which is less than or equal to a number
Syntax:
FLOOR(number)
RANDOM

RANDOM function used to generate random


number between 0 & 1 (1 will be excluded)
Syntax:
RANDOM( );

SETSEED

SETSEED function used to set a seed for the next


time that we call the RANDOM function
Syntax:
SETSEED(seed)
[seed can have a value between 1 and -1(both are
inclusive]

ROUND

ROUND function rounds a number to a specified


number of decimal places
Syntax:
ROUND(number)
POWER

POWER function returns m raised to the nth


power
Syntax:
POWER(m,n)

13. DATE-TIME FUNCTIONS

CURRENT_DATE

CURRENT_DATE function returns the current


date
Syntax:
CURRENT_DATE( )

CURRENT_TIME

CURRENT_TIME function returns the current


time with the time zone
Syntax:
CURRENT_TIME( )
CURRENT_TIMESTAMP

CURRENT_ TIMESTAMP function returns the


current date & current time with the time zone
Syntax:
CURRENT_ TIMESTAMP ( )

AGE

AGE function returns the difference between two


dates
Syntax:
AGE(date1,date2)

EXTRACT

EXTRACT function extract specified parts


from date
Syntax:
EXTRACT(‘unit’ FROM ‘date’)
[unit will be day,month,year,doy,decade,hour,minute,
second,etc.,]
14.PATTERN MATCHING
There are three different approaches to pattern
matching
• Using LIKE
• Using SIMILAR TO
• Using Regular Expression

• | denotes alternation (either of two alternatives).


• * denotes repetition of the previous item zero or more times.
• + denotes repetition of the previous item one or more times.
• ? denotes repetition of the previous item zero or one time.
• {m} denotes repetition of the previous item exactly m times.
• {m,} denotes repetition of the previous item m or more times.
• {m,n} denotes repetition of the previous item at least m and not
more than n times.
• Parentheses () can be used to group items into a single logical
item.
• A bracket expression [...] specifies a character class,

15.DATA TYPE CONVERSION FUNCTIONS

TO_CHAR

TO_CHAR function converts number/date to


String
Syntax:
TO_CHAR(value,format-mask)

TO_DATE

TO_DATE function converts string to date


Syntax:
TO_DATE(string,format-mask)

T0_NUMBER

T0_NUMBER function converts string to date


Syntax:
TO_NUMBER(string,format-mask)

Format Description

9 Numeric value with the specified number of digits

0 Numeric value with leading zeros

. decimal point
(period)

D decimal point that uses locale

, group (thousand) separator


(comma)
Format Description

FM Fill mode, which suppresses padding blanks and leading zeroes.

PR Negative value in angle brackets.

S Sign anchored to a number that uses locale

L Currency symbol that uses locale

G Group separator that uses locale

MI Minus sign in the specified position for numbers that are less than
0.

PL Plus sign in the specified position for numbers that are greater
than 0.

SG Plus / minus sign in the specified position

RN Roman numeral that ranges from 1 to 3999

TH or th Upper case or lower case ordinal number suffix

Pattern Description

Y,YYY year in 4 digits with comma

YYYY year in 4 digits

YYY last 3 digits of year


YY last 2 digits of year

Y The last digit of year

IYYY ISO 8601 week-numbering year (4 or more digits)

IYY Last 3 digits of ISO 8601 week-numbering year

IY Last 2 digits of ISO 8601 week-numbering year

I Last digit of ISO 8601 week-numbering year

BC, bc, AD or ad Era indicator without periods

B.C., b.c., A.D. ora.d. Era indicator with periods

MONTH English month name in uppercase

Month Full capitalized English month name

Month Full lowercase English month name

MON Abbreviated uppercase month name e.g., JAN, FEB, etc.

Mon Abbreviated capitalized month name e.g, Jan, Feb, etc.

Mon Abbreviated lowercase month name e.g., jan, feb, etc.

MM month number from 01 to 12

DAY Full uppercase day name

Day Full capitalized day name


Day Full lowercase day name

DY Abbreviated uppercase day name

Dy Abbreviated capitalized day name

Dy Abbreviated lowercase day name

DDD Day of year (001-366)

IDDD Day of ISO 8601 week-numbering year (001-371; day 1 of


the year is Monday of the first ISO week)

DD Day of month (01-31)

D Day of the week, Sunday (1) to Saturday (7)

ID ISO 8601 day of the week, Monday (1) to Sunday (7)

W Week of month (1-5) (the first week starts on the first day
of the month)

WW Week number of year (1-53) (the first week starts on the


first day of the year)

IW Week number of ISO 8601 week-numbering year (01-53;


the first Thursday of the year is in week 1)

CC Century e.g, 21, 22, etc.

J Julian Day (integer days since November 24, 4714 BC at


midnight UTC)

RM Month in upper case Roman numerals (I-XII; >


Rm Month in lowercase Roman numerals (i-xii; >

HH Hour of day (0-12)

HH12 Hour of day (0-12)

HH24 Hour of day (0-23)

MI Minute (0-59)

SS Second (0-59)

MS Millisecond (000-999)

US Microsecond (000000-999999)

SSSS Seconds past midnight (0-86399)

AM, am, PM or pm Meridiem indicator (without periods)

A.M., a.m., P.M. or Meridiem indicator (with periods)


p.m.
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

Project status reporting on a daily basis to onsite counterparts and client.


Daily Status Report
- Progress Highlight
- Blocker Status(Defect, Test Data, Clarification, Requirement update)
- Summary Test Execution(Failed, Passed, Blocked, NC %
- Test Execution GOAL(Effort Justification)
- Outage Details(Resource #/ Effort Loss/Person, Planned productive Hours/Actual productive hours/Effort Utilized in other Area)
- Test Case and defect dump.
- Resourcing

Difference between Test Strategy and Test Plan

Test Strategy

A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document

• Scope and Objectives • Test automation and tools


• Business issues • Testing measurements and metrics

• Roles and responsibilities • Risks and mitigation


• Communication and status reporting • Defect reporting and tracking
• Test deliverables • Change and configuration management

• Industry standards to follow • Training plan

Here is an example of an Agile Test Strategy Document Template

Test Plan

The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.

Components of the Test Plan document

• Test Plan id • Suspension criteria


• Introduction • Features pass or fail criteria
• Test items • Test environment (Entry criteria, Exit
criteria)
• Features to be tested • Test deliverables
• Features not to be tested • Staff and training needs
• Test techniques • Responsibilities
• Testing tasks • Schedule

Test matrices formula

Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100

Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100

Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%

Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100

Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100

Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100

Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100

Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100

Test Reports

1. Daily Status Report


2. Predictive Dashboard Report
3. Test Closure Report
(Purpose/Approach/TM Tool/Inscope-outscope/Requirement Traceability/Test Schedule/Test Summary
Highlights/Test Result Details/Lesson Learnt/Recommendations/Test Metrics /Risk/Test Deliverables)

Defect Severity & Priority

1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.

2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).

Effort Estimations

Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding

Risk management

The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.

The risk management process occurs twice, during:

1. Test planning
2. Test case design(end) or sometimes in the test execution phase

It is mandatory in case 1 but with case 2 it is more of a ‘need-basis’ situation

Risk Management Process

The generic process for Risk management involves 3 important stages:

1. Risk identification
2. Risk impact analysis
3. Risk mitigation

Risk identification

As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.

The main outcome of this step is: a list of risks.

This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.

Risks during Test Planning – Risk Based Testing Examples

The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.

#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.

#2. Not enough resources, resources on boarding too late (process takes around 15 days.)

#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.

#4. Scope not defined completely defined

#5. Natural disasters

#6. Non-availability of Independent Test environment and accessibility

#7. Delayed Testing Due To new Issues

At this point, you can choose to be as thorough as you would like, depending on the amount of time available.

Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.

Risk assessment/Risk impact analysis

Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.

High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.

Risk impact analysis table:

Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):

Risk Probability Impact

1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.

2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High

3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.

4. Scope not defined completely defined Medium Medium


Risk Probability Impact

5. Natural disasters Low Medium

6. Non-availability of Independent Test environment and accessibility Medium High

7. Delayed Testing Due To new Issues Medium High

Risk Mitigation

The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.

Risk Mitigation Techniques:

Here is an example of what the Risk’s table transforms into when this phase is complete:

Risk Prob. Impact Mitigation Plan

SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.

RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.

DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.

SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.

Teams and responsibilities have been spread to two different


geographic areas. In a catastrophic event in one of the areas, there will
Natural disasters Low Medium
resources in the other areas needed to continue (although at a slower
pace) the testing activities.

Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.

During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:

1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.

Risk Based Testing

Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.

It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,

• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.

Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,

• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:

• Process 1 – Describe all requirements in terms of Risk involved in the project


• Process 2 – In terms of risk assessment, prioritize the requirements
• Process 3 – Plan and define tests according to requirement prioritization
• Process 4 – Execute test according to prioritization and acceptance criteria.
HPQC Reports

Reports Included in the HP Quality Center Report Packs


Report Category
Free Standard Professional

Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs

Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects

Regression testing

Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.

Regression indicator (New/Mod/Beginning) /Regression Scope (Mandatory/Optional)/ Regression priority (High/Medium/Low)

1. End To End Regression


2. Application Specific Regression

End To End testing

End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

Project status reporting on a daily basis to onsite counterparts and client.


Daily Status Report
- Progress Highlight
- Blocker Status(Defect, Test Data, Clarification, Requirement update)
- Summary Test Execution(Failed, Passed, Blocked, NC %
- Test Execution GOAL(Effort Justification)
- Outage Details(Resource #/ Effort Loss/Person, Planned productive Hours/Actual productive hours/Effort Utilized in other Area)
- Test Case and defect dump.
- Resourcing

Difference between Test Strategy and Test Plan

Test Strategy

A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document

• Scope and Objectives • Test automation and tools


• Business issues • Testing measurements and metrics

• Roles and responsibilities • Risks and mitigation


• Communication and status reporting • Defect reporting and tracking
• Test deliverables • Change and configuration management

• Industry standards to follow • Training plan

Here is an example of an Agile Test Strategy Document Template

Test Plan

The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.

Components of the Test Plan document

• Test Plan id • Suspension criteria


• Introduction • Features pass or fail criteria
• Test items • Test environment (Entry criteria, Exit
criteria)
• Features to be tested • Test deliverables
• Features not to be tested • Staff and training needs
• Test techniques • Responsibilities
• Testing tasks • Schedule

Test matrices formula

Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100

Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100

Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%

Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100

Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100

Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100

Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100

Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100

Test Reports

1. Daily Status Report


2. Predictive Dashboard Report
3. Test Closure Report
(Purpose/Approach/TM Tool/Inscope-outscope/Requirement Traceability/Test Schedule/Test Summary
Highlights/Test Result Details/Lesson Learnt/Recommendations/Test Metrics /Risk/Test Deliverables)

Defect Severity & Priority

1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.

2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).

Effort Estimations

Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding

Risk management

The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.

The risk management process occurs twice, during:

1. Test planning
2. Test case design(end) or sometimes in the test execution phase

It is mandatory in case 1 but with case 2 it is more of a ‘need-basis’ situation

Risk Management Process

The generic process for Risk management involves 3 important stages:

1. Risk identification
2. Risk impact analysis
3. Risk mitigation

Risk identification

As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.

The main outcome of this step is: a list of risks.

This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.

Risks during Test Planning – Risk Based Testing Examples

The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.

#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.

#2. Not enough resources, resources on boarding too late (process takes around 15 days.)

#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.

#4. Scope not defined completely defined

#5. Natural disasters

#6. Non-availability of Independent Test environment and accessibility

#7. Delayed Testing Due To new Issues

At this point, you can choose to be as thorough as you would like, depending on the amount of time available.

Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.

Risk assessment/Risk impact analysis

Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.

High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.

Risk impact analysis table:

Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):

Risk Probability Impact

1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.

2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High

3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.

4. Scope not defined completely defined Medium Medium


Risk Probability Impact

5. Natural disasters Low Medium

6. Non-availability of Independent Test environment and accessibility Medium High

7. Delayed Testing Due To new Issues Medium High

Risk Mitigation

The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.

Risk Mitigation Techniques:

Here is an example of what the Risk’s table transforms into when this phase is complete:

Risk Prob. Impact Mitigation Plan

SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.

RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.

DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.

SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.

Teams and responsibilities have been spread to two different


geographic areas. In a catastrophic event in one of the areas, there will
Natural disasters Low Medium
resources in the other areas needed to continue (although at a slower
pace) the testing activities.

Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.

During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:

1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.

Risk Based Testing

Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.

It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,

• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.

Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,

• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:

• Process 1 – Describe all requirements in terms of Risk involved in the project


• Process 2 – In terms of risk assessment, prioritize the requirements
• Process 3 – Plan and define tests according to requirement prioritization
• Process 4 – Execute test according to prioritization and acceptance criteria.
HPQC Reports

Reports Included in the HP Quality Center Report Packs


Report Category
Free Standard Professional

Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs

Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects

Regression testing

Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.

Regression indicator (New/Mod/Beginning) /Regression Scope (Mandatory/Optional)/ Regression priority (High/Medium/Low)

1. End To End Regression


2. Application Specific Regression

End To End testing

End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Sample Interview Question and
Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

Project status reporting on a daily basis to onsite counterparts and client.


Daily Status Report
- Progress Highlight
- Blocker Status(Defect, Test Data, Clarification, Requirement update)
- Summary Test Execution(Failed, Passed, Blocked, NC %
- Test Execution GOAL(Effort Justification)
- Outage Details(Resource #/ Effort Loss/Person, Planned productive Hours/Actual productive hours/Effort Utilized in other Area)
- Test Case and defect dump.
- Resourcing

Difference between Test Strategy and Test Plan

Test Strategy

A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document

• Scope and Objectives • Test automation and tools


• Business issues • Testing measurements and metrics

• Roles and responsibilities • Risks and mitigation


• Communication and status reporting • Defect reporting and tracking
• Test deliverables • Change and configuration management

• Industry standards to follow • Training plan

Here is an example of an Agile Test Strategy Document Template

Test Plan

The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.

Components of the Test Plan document

• Test Plan id • Suspension criteria


• Introduction • Features pass or fail criteria
• Test items • Test environment (Entry criteria, Exit
criteria)
• Features to be tested • Test deliverables
• Features not to be tested • Staff and training needs
• Test techniques • Responsibilities
• Testing tasks • Schedule

Test matrices formula

Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100

Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100

Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%

Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100

Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100

Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100

Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100

Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100

Test Reports

1. Daily Status Report


2. Predictive Dashboard Report
3. Test Closure Report
(Purpose/Approach/TM Tool/Inscope-outscope/Requirement Traceability/Test Schedule/Test Summary
Highlights/Test Result Details/Lesson Learnt/Recommendations/Test Metrics /Risk/Test Deliverables)

Defect Severity & Priority

1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.

2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).

Effort Estimations

Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding

Risk management

The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.

The risk management process occurs twice, during:

1. Test planning
2. Test case design(end) or sometimes in the test execution phase

It is mandatory in case 1 but with case 2 it is more of a ‘need-basis’ situation

Risk Management Process

The generic process for Risk management involves 3 important stages:

1. Risk identification
2. Risk impact analysis
3. Risk mitigation

Risk identification

As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.

The main outcome of this step is: a list of risks.

This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.

Risks during Test Planning – Risk Based Testing Examples

The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.

#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.

#2. Not enough resources, resources on boarding too late (process takes around 15 days.)

#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.

#4. Scope not defined completely defined

#5. Natural disasters

#6. Non-availability of Independent Test environment and accessibility

#7. Delayed Testing Due To new Issues

At this point, you can choose to be as thorough as you would like, depending on the amount of time available.

Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.

Risk assessment/Risk impact analysis

Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.

High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.

Risk impact analysis table:

Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):

Risk Probability Impact

1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.

2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High

3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.

4. Scope not defined completely defined Medium Medium


Risk Probability Impact

5. Natural disasters Low Medium

6. Non-availability of Independent Test environment and accessibility Medium High

7. Delayed Testing Due To new Issues Medium High

Risk Mitigation

The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.

Risk Mitigation Techniques:

Here is an example of what the Risk’s table transforms into when this phase is complete:

Risk Prob. Impact Mitigation Plan

SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.

RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.

DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.

SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.

Teams and responsibilities have been spread to two different


geographic areas. In a catastrophic event in one of the areas, there will
Natural disasters Low Medium
resources in the other areas needed to continue (although at a slower
pace) the testing activities.

Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.

During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:

1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.

Risk Based Testing

Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.

It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,

• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.

Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,

• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:

• Process 1 – Describe all requirements in terms of Risk involved in the project


• Process 2 – In terms of risk assessment, prioritize the requirements
• Process 3 – Plan and define tests according to requirement prioritization
• Process 4 – Execute test according to prioritization and acceptance criteria.
HPQC Reports

Reports Included in the HP Quality Center Report Packs


Report Category
Free Standard Professional

Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs

Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects

Regression testing

Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.

Regression indicator (New/Mod/Beginning) /Regression Scope (Mandatory/Optional)/ Regression priority (High/Medium/Low)

1. End To End Regression


2. Application Specific Regression

End To End testing

End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Sample Interview Question and
Answers prepared by Haradhan Pal

YouTube Channel Link:


https://www.youtube.com/c/HaradhanAutomationL
ibrary?sub_confirmation=1

Project status reporting on a daily basis to onsite counterparts and client.


Daily Status Report
- Progress Highlight
- Blocker Status(Defect, Test Data, Clarification, Requirement update)
- Summary Test Execution(Failed, Passed, Blocked, NC %
- Test Execution GOAL(Effort Justification)
- Outage Details(Resource #/ Effort Loss/Person, Planned productive Hours/Actual productive hours/Effort Utilized in other Area)
- Test Case and defect dump.
- Resourcing

Difference between Test Strategy and Test Plan

Test Strategy

A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document

• Scope and Objectives • Test automation and tools


• Business issues • Testing measurements and metrics

• Roles and responsibilities • Risks and mitigation


• Communication and status reporting • Defect reporting and tracking
• Test deliverables • Change and configuration management

• Industry standards to follow • Training plan

Here is an example of an Agile Test Strategy Document Template

Test Plan

The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.

Components of the Test Plan document

• Test Plan id • Suspension criteria


• Introduction • Features pass or fail criteria
• Test items • Test environment (Entry criteria, Exit
criteria)
• Features to be tested • Test deliverables
• Features not to be tested • Staff and training needs
• Test techniques • Responsibilities
• Testing tasks • Schedule

Test matrices formula

Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100

Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100

Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%

Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100

Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100

Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100

Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100

Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100

Test Reports

1. Daily Status Report


2. Predictive Dashboard Report
3. Test Closure Report
(Purpose/Approach/TM Tool/Inscope-outscope/Requirement Traceability/Test Schedule/Test Summary
Highlights/Test Result Details/Lesson Learnt/Recommendations/Test Metrics /Risk/Test Deliverables)

Defect Severity & Priority

1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.

2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).

Effort Estimations

Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding

Risk management

The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.

The risk management process occurs twice, during:

1. Test planning
2. Test case design(end) or sometimes in the test execution phase

It is mandatory in case 1 but with case 2 it is more of a ‘need-basis’ situation

Risk Management Process

The generic process for Risk management involves 3 important stages:

1. Risk identification
2. Risk impact analysis
3. Risk mitigation

Risk identification

As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.

The main outcome of this step is: a list of risks.

This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.

Risks during Test Planning – Risk Based Testing Examples

The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.

#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.

#2. Not enough resources, resources on boarding too late (process takes around 15 days.)

#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.

#4. Scope not defined completely defined

#5. Natural disasters

#6. Non-availability of Independent Test environment and accessibility

#7. Delayed Testing Due To new Issues

At this point, you can choose to be as thorough as you would like, depending on the amount of time available.

Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.

Risk assessment/Risk impact analysis

Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.

High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.

Risk impact analysis table:

Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):

Risk Probability Impact

1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.

2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High

3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.

4. Scope not defined completely defined Medium Medium


Risk Probability Impact

5. Natural disasters Low Medium

6. Non-availability of Independent Test environment and accessibility Medium High

7. Delayed Testing Due To new Issues Medium High

Risk Mitigation

The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.

Risk Mitigation Techniques:

Here is an example of what the Risk’s table transforms into when this phase is complete:

Risk Prob. Impact Mitigation Plan

SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.

RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.

DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.

SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.

Teams and responsibilities have been spread to two different


geographic areas. In a catastrophic event in one of the areas, there will
Natural disasters Low Medium
resources in the other areas needed to continue (although at a slower
pace) the testing activities.

Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.

During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:

1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.

Risk Based Testing

Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.

It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,

• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.

Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,

• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:

• Process 1 – Describe all requirements in terms of Risk involved in the project


• Process 2 – In terms of risk assessment, prioritize the requirements
• Process 3 – Plan and define tests according to requirement prioritization
• Process 4 – Execute test according to prioritization and acceptance criteria.
HPQC Reports

Reports Included in the HP Quality Center Report Packs


Report Category
Free Standard Professional

Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs

Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects

Regression testing

Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.

Regression indicator (New/Mod/Beginning) /Regression Scope (Mandatory/Optional)/ Regression priority (High/Medium/Low)

1. End To End Regression


2. Application Specific Regression

End To End testing

End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Levels In
Software Testing
Module / Unit
Testing

It checks subprograms, procedures,


routines, and subroutines in a program.

01
Integration
Testing

Here, the combined parts of an


application of software are tested to
check if they function correctly or not.

02
System
Testing

System testing tests the entire system


or software or any application.

03
Acceptance
Testing
The quality assurance team does
this testing to check if the clients'
requirements are met or not.

04
Software Testing

Cyber Security

We provide a complete solution


for your Testing needs
Get in touch with us today

www.precisetestingsolution.com
TEST PLAN

AUG 25, 2022


Version History:

Version Revised By Summary Approval Date

Table of Contents
1. Introduction 3
2. Scope 3

3. Test Objective 4

4. Reference Document 4

5. Detailed Test Approach 4

Test Strategy

Test Schdeule

Problem Severity Classifcation:

Test Resources

Pass/Fail Criteria:

Environment

Test Cases and Test Scenarios


Tools and defect Tracking

Final Test Report

Exit Criteria

1. Introduction
The Test Plan outlines the scope, approach, resources, and schedule of all testing
activities. It identifes the items and features to be tested; types of testing. It contains a
detailed and executable strategy for conducting. It defnes the detailed testing objective
specifc to a particular system, the testing approach, test environment, test conditions, and
the test plan.

2. Scope
The scope of this test plan is to ensure websiteX meets all of its technical, functional and
business requirements. The purpose of this document is to describe the overall test plan
and strategy for testing the website. The approach described in this document provides the
framework for all the testing related to website. This document will also be updated as
required with the requirement updates. We also need to make sure that all the expected
results are achieved.

2.1. Out of Scope

3. Test Objectives
The general test objectives are to test the correctness of the generation of the
interface data fle, the content of the interface data fle, and any error conditions. The
quality objectives of testing the website are to ensure complete validation of the
business and software requirements:

Verify software requirements are complete and accurate


Perform detailed test planning
Identify testing standards and procedures that will be used while testing the
website
Prepare and document test scenarios and test cases
Manage defect tracking process
Finalize the prject for release

Reference Documents
—--------

5. Detailed Test Approach


Detialed testing phases and methodologies are mentioned below. We will follow the
protocols of each phase and achieve the highest results.

Requirement Analysis
Design Testing
Functionality Testing
Verify each functionlaity of the system is working as per requirement
Testing the links
Testing the forms
Cookies Testing
Validation (HTML/CSS/PHP)
Database Testing
Integration Test Specifcation
API Testing
Usability Testing
Compatibility Testing
Browser Compatibility
OS compatibility
Mobile browsing
Performance Testing
Load Testing
Stress Testing
Security Testing
Automation Testing
Smoke Testing
Beta Testing

5.1 Requirement Analysis


Requirements analysis is critical to the success or failure of a systems or software project
so we have to verify, validate and confrm each requirement. Requirements must be
validated on the basis of User Experience, User Interface, How to test the requirements,
Requiremnts are up to date.

Make sure the major scenarios and requirements are mentioned in the document. If there
is something missing, highlight the missing requiremnts and also suggest improvements if
there is any.

Analyze the following Requirements

—-----------

5.2 Design Testing


Test all the designs and verify all the designs must be correct as per the requirements.

And also make sure the designs for all the specifed languages and dark themes.

5.3 Functionality Testing


Test the functional requirements and determine every function of the software is acting in
accordance with the pre-determined requirements and tasks. At website, Performed
testing of all the links in web pages, checking the database connections, forms used in the
web pages for submitting or getting information from user & Cookie testing. Functional
testing is extended to the types given below.

5.3.1 Testing all the Links:


Test the outgoing links from all the pages from a specifc domain under test.
Test all internal links.
Test links jumping on the same pages.
Test links used to send the email to admin or other users from web pages.
Test to check if there are any orphan pages.
Lastly in link checking, check for broken links in all above-mentioned links.

5.3.2 Testing of the forms on the web pages:


Forms are the essential and integral parts of website . Forms are used to get information
from users and to keep interaction with them.

The following should be checked on the forms:

Check all the validations on each feld.


Check for the default values of felds.
Wrong inputs to the felds in the forms.
Options to create forms, if any, form delete, view or modify the forms.
Check that no empty forms are created.
There are different feld validations like email-id’s, user fnancial
information, date, etc
All the above validations should be checked in a manual or an
automated way.

5.3.3 Cookie Testing:


Cookies are small fles stored on a user machine that are basically used to maintain the
sessions such as the ‘login sessions’. Test the website to verify

Test the application by enabling or disabling the cookies in your


browser options
Test if the cookies are encrypted before writing to user machine
During the test for session cookies (i.e. cookies expire after the
sessions ends) check for login sessions and user stats after session end
Check effect on application security by deleting the cookies

5.3.4 Validation (HTML/CSS):


HTML/CSS validation is very important for optimizing the website for

search engines.

The site has full and correct Doctype


The site uses character set
The site uses valid XHTML
The site uses valid CSS
The site has no unnecessary ids or classes
The site uses well structured code
The site has no broken links
The site has clearly defned visited links

5.3.5 Database Testing:


Check for data integrity and errors while you edit, delete, modify the forms or do any
database related functionality.
Check if all the database queries are executing correctly and data is retrieved
correctly and also updated correctly.

Also we need to validate the Database by executing the queries.

Comp
5.4. API Testing
Set of procedures to verify the expected functionality, reliability, and security and ensure
the correct interaction between backend and frontend. To validate the logic of the build
architecture within a short amount of time. Each api test consists of some test actions
mentioned below. Further details of API Testing will be covered in API Test Plan

Verify the URL accordingly environment


Verify required request headers and their correct values
Verify response payload
Verify correct HTTP status code and response headers
Verify expected result and correct application state
Verify correct performance sanity

5.6. Usability Testing:


The goals of usability testing include establishing a baseline of user performance,
establishing and validating user performance measures, and identifying potential design
concerns to be addressed in order to improve the effciency, productivity, and end-user
satisfaction.

The usability test objectives are:

To determine design inconsistencies and usability problem areas within the user
interface and content areas.
Potential sources of error may include:
Navigation errors – failure to locate functions, excessive keystrokes to
complete a function, failure to follow recommended screen fow.
Presentation errors – failure to locate and properly act upon desired
information in screens, selection errors due to labeling ambiguities.
Control usage problems – improper toolbar or entry feld usage.
Exercise the application or web site under controlled test conditions with representative
users. Data will be used to access whether usability goals regarding an effective,
effcient, and well-received user interface have been achieved.
Establish baseline user performance and user-satisfaction levels of the use interface for
future usability evaluations.
Basic Usability:
The site should have a clear hierarchy.
Headings clearly indicate the structure of the document
Navigation should be easy to understand
Navigation is consistent throughout the site
The site uses underlined links
The site uses consistent and appropriate language
The site has easy to fnd sitemap and contact page
The site has a search tool
The site has a link to home page on every page
The site has clearly defned visited links

5.7. Compatibility Testing:


5.7.1 Browser compatibility
Some requirements are very dependent on browsers. Different browsers have different
confgurations and settings that the web page should be compatible with. The web site
coding should be cross browser platform compatible. Test the UI of website, functionality,
security checks or validations then stresses browser compatibility testing of the web
application. Test web application on different browsers like Internet explorer, Chrome,
Firefox, Netscape navigator, AOL, Safari, Opera browsers with different versions

5.7.2 OS compatibility:
Some functionality in the web application may not be compatible with all operating
systems. All new technologies used in web development like graphics designs, interface
calls like different API’s may not be available in all Operating Systems. Testing the web
application on different operating systems like Windows, Unix, MAC, Linux, Solaris with
different OS favors.

5.7.3. Mobile browsing:


Mobile browsing is also an integral part of browsing. Testing the web pages on mobile
browsers is highly important. Compatibility issues may be there on mobile. Currently ,the
system is not designed for mobile browsing, although this is an area we can add in future.

5.8. Performance testing:


Website should sustain heavy load. website performance testing should include: Load
Testing & Web Stress Testing. Test the website on different Internet connection speeds.

5.8.1. Load Testing:


Test website if many users are accessing or requesting the same page. Can the system
sustain peak load times? Site should handle many simultaneous user requests, large input
data from users, Simultaneous connection to DB, heavy load on specifc pages etc. For load
testing we will use blazemeter and robot scripts.

5.8.2. Stress Testing:


Generally stress means stretching the system beyond its specifcation limits. Web stress
testing is performed to break the site by giving stress and check how the system reacts to
stress and how the system recovers from crashes. Stress is generally given on input felds,
login and sign-up areas. In website performance testing website functionality on different
operating systems, different hardware platforms are checked for software, hardware
memory leakage errors. For stress testing we will use jmeter and blazemeter.

5.9. Security Testing:


Test by pasting the internal URL directly into the browser address bar without login.
Internal pages should not open.
If you are logged in using a username and password and browsing internal pages
then try changing URL options directly. I.e. while checking website Try directly
changing the URL site ID parameter to a different site ID, which is not related to,
logged in user. Access should be denied for this user to view others' stats.
Try some invalid inputs in input felds like login username, password, and input text
boxes. Check the system reaction on all invalid inputs.
Web directories or fles should not be accessible directly unless given
download option.
Inspect the pages and verify Elements, Console and Sources.
Test the CAPTCHA for automated script logins.
Test if SSL is used for security measures. If used proper message should
get displayed when the user switches from non-secure http:// pages to secure
https:// pages and vice versa.
All transactions, error messages, security breach attempts should get logged-in log fles
somewhere on the web server.
Check the security points while the communication between frontend and backend.
It may includes:
User IP

Accept-Language

SESSION_ID/Device ID

Signature

User-Agent
Furthermore we will use Zap for security testing. It is an end-to-end web application
security scanner. This will give us a 360-degree view of the security of our website. It
is important to have an understanding of how the client (browser) and the server
communicate using HTTP. the tester should at least know the basics of SQL injection
and XSS.

Automation Testing:

5.10. Automation Testing:


Automate all the implemented functinlaities of the website . Creation of the automation test
cases. Details of Automation testing will be discussed and covered inside the Test Plan of
automation testing.

Write the test cases in a test rail for specifc features.


Analysis of test cases which are possible to be automated
Plan the test cases and how to execute all the test cases.
Write the test cases w.r.t environment.
write the logic for how to validate the test.
Write the pass/fail criteria agaist each test case.
run and actually verify the test.
Integrate all the test cases of each feature/module

5.11. Smoke Testing:


Smoke Testing is a software testing process that determines whether the deployed
software build is stable or not. Insid the smoke testing QA Engineer will make sure all the
critical functionalities are working fne. We will create a checklist of smoke testing.

Smoke testing will be performed at two stages. Once new features are added, the other is
before fnalizing the build for Production/live.

Create the checklist for smoke testing.

5.12. Beta Testing


Beta testing is basically a relase for specifc users to use a product in a production
environment to uncover any bugs or issues before a general release.

Beta testing is the fnal round of testing before releasing a product to a wide audience. The
objective is to uncover as many bugs or usability issues as possible in this controlled
setting. QA will also a perfrom the beta Testing.
6. Test Strategy
The overall strategy of this testing initiative is manual, black box testing. We are
testing the data, interface part and mplemented system in detail. The testing at the
SAP end of the interface will be covered by the SAP functional testing. Follow the
testing phases and techniques mentioned inside “Detailed Test Approach”. All type
of testing are covered in this document.

Some of the test specifcations use test data which needs to be set-up in the test
environment prior to executing the test cases.

For each level of testing, a separate test plan is prepared with the following set of
deliverables:

Test Cases/Test Sceanrios


Features to be tested
Items to be tested
Pass / Fail criteria
Bugs cycle
Automation
Expected Results
Actual Results

Test Schdeule
The test schedule is the timeline of acceptance testing activities and deliverable dates.

Testing activities are mentioned below.

Requirement Analysis.
Design Testing
Develop test scenarios
Develop test cases
Review scenarios/test cases for accuracy, completeness and sequence (confrm
test data is correct)
Integration testing
API Testing
Regression Testing
Functionality Testing
Database Testing
Integration Test Specifcation
Usability Testing
Compatibility Testing
Performance Testing
Security Testing
UAT Testing
Automation Testing
Smoke Testing
Beta Testing

Problem/Bug Severity Classifcation:


The identifed severity for each problem implies a general reward for resolving it, and a
general risk for not addressing it, in the current release.

Severity 1 - Crash or High impact problems that often prevent a user/host from correctly
completing an experience/booking.

Severity 2 - Moderate to high frequency problems with the functionality/UI or UX impact

Severity 3 - Either moderate problems with low frequency or low problems with moderate
frequency; these are minor annoyance problems faced by a number of participants.

Severity 4 - Low impact problems faced by few participants; there is low risk of not
resolving these problems. Reward for resolution is typically exhibited in increased user
satisfaction.

9. Test Resources
Here is the list of resources with the roles those will work on website

1.
2.

10. Pass/Fail Criteria:


Create the test cases and mention the expected results/pass criteria against each testcase.

11. Environment
Start testing on a staging server once a certain level is achieved, then move to Production
and give the fnal approval at Production. All the experiments should be performed at
staging. Testing data must be private at Production.
12. Test Cases and Test Scenarios
Write down the detailed test cases on the basis of requirement, technical doecument and test
plan. For testcases use the Google sheet and use the Jira for bug, suggestion reporting.

13. Tools and defect Tracking

Jira wil be used for defect reporting and issue bugs/defects management and
traceability.

14. Final Test Report


Test closure reports shall be generated for each testing phase as the testing phase gets

completed.

15. Exit Criteria


All the test cases and test scenarios must be passed. Every user must get the music
recommendation as per their interests.
SQL exercises, based on dreamhome database
Datatbase system:
1. Login to mysql database server imc.kean.edu using xxx account
ANS:
mysql -u xxx -p -h imc.kean.edu
2. Switch to database dreamhome
ANS:
use dreamhome;
3. Show all tables in dreamhome database
ANS:
show tables;
4. Show the table structure (column name, datatype, keys, etc) of Staff table
ANS:
desc Staff;

SELECT:
5. Show all the rows and all the columns of Staff table
ANS:
SELECT * FROM Staff;
6. Produce a list of salaries for all staff, showing only the staff number, the first and last names, and
the salary details.
ANS:
SELECT staffNo, fName, IName, salary FROM Staff;
7. List full details of all hotels in London.
ANS:
SELECT * FROM Hotel WHERE city = 'London';
8. List the unique property numbers of all properties that have been viewed.
ANS:
SELECT DISTINCT propertyNo FROM Viewing;
9. Write a SQL query to list the staff who work in London. Please show their first name, last name and
branchno.
ANS:
SELECT fname,lname,b.branchno FROM Staff s, Branch b
WHERE s.branchno=b.branchno and b.city='London';
10. Produce a list of monthly salaries for all staff, showing the staff number, the first and last names,
and the salary details.
ANS:
SELECT staffNo, fName, IName, salary/12 FROM Staff;
11. List all staff with a salary greater than $10,000.
ANS:
SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > 10000;
12. Write a SQL query to display the name for vendor lives in New York with zipcode 07811.
(refer to A_Vendors)
ANS:
SELECT name from A_Vendors where State = 'NY' and Zipcode='07811';
13. Write a SQL query to list the unique position for female staff with salary less than 10000.
ANS:
SELECT distinct position FROM Staff WHERE sex='F' and salary < 10000;
14. List the addresses of all branch offices in London or Glasgow.
ANS:
SELECT street FROM Branch WHERE city = 'London' OR city = 'Glasgow';
15. Write a SQL query to display product names that make profit < 20. (refer to A_Products)
ANS:
SELECT name FROM A_Products WHERE sell_price - cost < 20;
16. List all staff with a salary between $20,000 and $30,000.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary BETWEEN 20000 AND 30000;
ANS 2:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > = 20000 AND salary < = 30000;
17. List all managers and supervisors.
ANS:
SELECT staffNo, fName, IName, position FROM Staff WHERE position IN ('Manager', 'Supervisor');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff WHERE position = 'Manager' OR position =
'Supervisor';
18. What is the output of the following SQL query?
SELECT clientno, propertyno FROM Viewing WHERE comment!='';
ANS:
+----------+------------+
| clientno | propertyno |
+----------+------------+
| CR56 | PA14 |
| CR62 | PA14 |
| CR76 | PG4 |
+----------+------------+
19. List all double or family rooms with a price below 40.00 per night, in ascending order of price.
ANS:
SELECT * FROM Room WHERE price < 40 AND type IN ('double', 'family') ORDER BY price;
20. Find all owners with the string ‘Glasgow’ in their address.
ANS:
SELECT ownerNo, fName, IName, address, telNo
FROM PrivateOwner WHERE address LIKE '%Glasgow%';
21. Write a SQL query to display the total number of Customers living in Union.
ANS:
SELECT count(name) FROM A_Customers WHERE address like '%Union%';
22. List the details of all viewings on property PG4 where a comment has not been supplied.
ANS:
SELECT clientNo, viewDate FROM Viewing WHERE propertyNo = 'PG4' AND comment IS NULL;
23. Produce a list of salaries for all staff, arranged in descending order of salary.
ANS:
SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC;
24. Produce an abbreviated list of properties arranged in order of property type.
ANS:
SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type;
25. List the names and addresses of all guests in London, alphabetically ordered by name.
ANS:
SELECT guestName, guestAddress FROM Guest
WHERE guestAddress LIKE '%London%' ORDER BY guestName;

AGGREGATE FUNCTIONS, GROUP BY:


26. Write a SQL query to display the number of unique products been reviewed (A_Reviews table).
ANS:
SELECT count(distinct p_id) FROM A_Reviews;
27. Write a SQL query to display the total salary of all staff.
ANS:
SELECT SUM(salary) from Staff;
28. What is the output of the following SQL query?
SELECT max(price) as myMax FROM Room WHERE type='family';
ANS:
+-------+
| myMax |
+-------+
| 59.99 |
+-------+
29. What is the output of the following SQL query?
SELECT type, count(*) as ct,max(price) FROM Room group by type having ct > 3;
ANS:
+--------+----+------------+
| type | ct | max(price) |
+--------+----+------------+
| double | 4 | 86.00 |
| single | 5 | 58.00 |
+--------+----+------------+
30. Write a SQL query to list the unique branchno that branch has at least two female staff.
ANS:
SELECT distinct branchno FROM Staff group by branchno,sex having count(sex) >= 2 and sex='F';
31. Write a SQL query to display the total revenues of all products. The output column name should be
“revenue”.
ANS:
SELECT sum(sell_price*quantity) as revenue FROM A_Products;
32. Write the SQL query to show the branchno and the maximum salary for each branch in the Staff
table. The output should be sorted from high to low based on the max salary of each branch;
ANS:
SELECT branchno, max(salary) FROM Staff group by branchno order by max(salary) desc;
33. Can we run the following SQL query without any problem?
SELECT fname FROM Staff WHERE salary > max(salary);
ANS:
NO, the statement invalid use of group function. Aggregation cannot be in WHERE.
34. Write the SQL query to find how many properties cost more than $350 per month to rent?
ANS:
SELECT COUNT(*) AS myCount FROM PropertyForRent WHERE rent > 350;
35. How many different properties were viewed in May 2013?
ANS:
SELECT COUNT(DISTINCT propertyNo) AS myCount
FROM Viewing WHERE viewDate BETWEEN '2013-05-01' AND '2013-05-31';
36. Find the total number of Managers and the sum of their salaries.
ANS:
SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff WHERE position =
'Manager';
37. Find the minimum, maximum, and average staff salary.
ANS:
SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg FROM Staff;
38. What is the total revenue per night from all double type rooms if all rooms are booked?
ANS:
SELECT SUM(price) FROM Room WHERE type = 'double';
39. Find the number of staff working in each branch and the sum of their salaries.
ANS:
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff GROUP BY
branchNo ORDER BY branchNo;
ANS 2:
SELECT branchNo, ( SELECT COUNT(staffNo) AS myCount FROM Staff s
WHERE s.branchNo = b.branchNo ), ( SELECT SUM(salary) AS mySum FROM Staff s WHERE
s.branchNo = b.branchNo )FROM Branch b ORDER BY branchNo;
40. For each branch office with more than one member of staff, find the number of staff working in
each branch and the sum of their salaries.
ANS:
SELECT branchNo, COUNT(staffNo) AS myCount, SUM(salary) AS mySum
FROM Staff GROUP BY branchNo HAVING COUNT(staffNo) > 1 ORDER BY branchNo;
41. List the hotel name and the number of rooms in each hotel.
ANS:
SELECT h.hotelname, COUNT(r.roomNo) AS count
FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
42. What is the output of the following SQL statement?
SELECT count(comment) FROM Viewing;
ANS:
+----------------+
| count(comment) |
+----------------+
| 4 |
+----------------+
43. Show the total revenue per night for the double type room if all rooms are booked.
ANS:
SELECT SUM(price) FROM Room WHERE type = 'double';

SUBQUERY:
44. Write a SQL query to find the staff name (first name, last name) who has salary higher than the
average salary of branchno =’B003’;
ANS:
SELECT fname,lname FROM Staff where salary > (select avg(salary) from Staff
WHERE branchno ='B003');
45. Can we run the following query without any problem?
SELECT city FROM Branch WHERE branchNo = (SELECT branchNo FROM Staff where sex='F');
ANS:
Error, Subquery returns more than 1 row. Cannot use =, should use IN
46. What is the output of the following SQL query?
SELECT c.name FROM A_Customers c WHERE c.id NOT in (SELECT c_id FROM A_Reviews);
ANS:
+-------+
| name |
+-------+
| BJ2 |
| BJ3 |
| Judy1 |
| Judy2 |
+-------+
47. What is the output of the following SQL query?
SELECT count(distinct(city)) as myCt FROM Hotel WHERE hotelno in (SELECT hotelno FROM Room
WHERE type='single');
ANS:
+------+
| myCt |
+------+
| 3 |
+------+
48. Write a SQL query to display the staffno and working branch city for the staff who has the lowest
salary.
ANS:
SELECT s.staffno,b.city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and s.salary in (SELECT min(salary) FROM Staff);
49. List the staff who work in the branch at ‘163 Main St’.
ANS:
SELECT staffNo, fName, IName, position FROM Staff
WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff s, Branch b
WHERE s.branchNo = b.branchNo and street = '163 Main St';
50. List all guests staying at the Grosvenor Hotel from April 1st to August 31st, 2004.
ANS:
SELECT * FROM Guest WHERE guestNo in (
SELECT guestNo FROM Booking
WHERE dateFrom >= date('2004-04-01') AND dateFrom <= date('2004-08-31')
AND hotelNo = (SELECT hotelNo FROM Hotel WHERE hotelName = 'Grosvenor'));
51. List all staff whose salary is greater than the average salary, and show by how much their salary is
greater than the average.
ANS:
SELECT staffNo, fName, LName, position, (salary - (SELECT AVG(salary) FROM Staff)) AS salDiff FROM
Staff WHERE salary > (SELECT AVG(salary) FROM Staff);
ANS 2:
SELECT staffNo, fName, LName, position, (salary-a.avg1) AS salDiff
FROM Staff s, (SELECT AVG(salary) as avg1 FROM Staff) a WHERE salary > a.avg1;
52. List the properties that are handled by staff who work in the branch at ‘163 Main St’.
ANS:
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent WHERE staffNo IN (SELECT staffNo
FROM Staff WHERE branchNo = (SELECT branchNo
FROM Branch WHERE street = '163 Main St'));
53. Find all staff whose salary is larger than the salary of at least one member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > SOME (SELECT salary FROM Staff WHERE branchNo = 'B003');
54. Find all staff whose salary is larger than the salary of every member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > ALL (SELECT salary FROM Staff WHERE branchNo = 'B003');
55. Write a SQL query to show client names who didn’t give reviews (Viewing table).
ANS:
SELECT c.fname,c.lname FROM Client c
WHERE c.clientno NOT in (SELECT clientno FROM Viewing);
56. What is the most commonly booked room type for each hotel in London?
ANS:
select hotelname, type, max_ct
from
( select hotelno, max(ct) max_ct from
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) t
group by hotelno ) n,
Hotel h,
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) r
where n.hotelno=h.hotelno and r.hotelno=n.hotelno and h.city='London'and max_ct=ct;

57. Write a SQL query to display the cheapest product name (A_Products table) and its price.
ANS:
SELECT name, sell_price FROM A_Products
WHERE sell_price = (SELECT min(sell_price) FROM A_Products);

(INNSER) JOIN
58. How many rows and columns will be generated from the following SQL query?
SELECT * FROM A_Students, A_Courses;
ANS:
6 columns and 8 rows
59. Write a SQL statement to show the product names provided by vendor “James”.
(refer to A_Products, A_Vendors tables)
ANS:
SELECT p.name FROM A_Products p, A_Vendors v WHERE v.name='James' and p.V_Id=v.V_Id;
60. Write a SQL query to show the first name who works at London and has salary higher than 10000.
ANS:
SELECT fname FROM Branch b, Staff s
WHERE b.branchno=s.branchno and b.city='London' and s.salary > 10000;
61. List the names of all clients who have viewed a property, along with any comments supplied.
ANS:
SELECT c.clientNo, fName, IName, propertyNo, comment
FROM Client c, Viewing v WHERE c.clientNo = v.clientNo;
62. Write a SQL query to list employee names (first name, last name) and their Supervisor names (first
name, last name). The output header must clearly indicates who is employee and Supervisor. (refer
to A_Employee table)
ANS:
SELECT e.fname as E_fname, e.lname as E_lname, m.fname as M_fname, m.lname as M_lname
FROM A_Employee e, A_Employee m WHERE e.super_ssn=m.ssn;
63. For each branch office, list the staff numbers and names of staff who manage properties and the
properties that they manage.
ANS:
SELECT s.branchNo, s.staffNo, fName, IName, propertyNo
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
ORDER BY s.branchNo, s.staffNo, propertyNo;
64. For each branch, list the staff numbers and names of staff who manage properties, including the city
in which the branch is located and the properties that the staff manage.
ANS:
SELECT b.branchNo, b.city, s.staffNo, fName, IName, propertyNo
FROM Branch b, Staff s, PropertyForRent p
WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo
ORDER BY b.branchNo, s.staffNo, propertyNo;
65. Display the product names and the comments that customer BJ1 gave.
(refer to A_Cusomters, A_Reviews, A_Products)
ANS:
SELECT p.name, comments FROM A_Customers c, A_Reviews r, A_Products p
WHERE c.id=r.c_id and p.id=r.p_id and c.name='BJ1' ;
66. List the guestname, hotelname, number of days stayed, and the total amount needed to pay to the
hotel for every guest.
ANS:
select guestname, hotelname, datediff(dateto,datefrom), sum(datediff(dateto,datefrom)*price)
from Guest g, Hotel h, Room r, Booking b
where h.hotelno=b.hotelno and r.roomno=b.roomno and g.guestno=b.guestno
and dateto is not null group by guestname,hotelname;
67. Find the number of properties handled by each staff member, along with the branch number of the
member of staff.
ANS:
SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo ORDER BY s.branchNo, s.staffNo;
68. Find all staff who work in a London branch office.
ANS:
SELECT staffNo, fName, IName, position
FROM Staff s WHERE EXISTS (SELECT * FROM Branch b
WHERE s.branchNo = b.branchNo AND city = 'London');
ANS 2:
SELECT staffNo, fName, IName, position
FROM Staff s, Branch b WHERE s.branFchNo = b.branchNo AND city = 'London';

OUTER JOIN:
69. List all branch offices and any properties that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
70. List all properties and any branch offices that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
71. List the branch offices and properties that are in the same city along with any unmatched branches
or properties.
ANS:
SELECT b.*, p.* FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;
72. How many rows will be generated from the following SQL statement:
SELECT * FROM Staff s RIGHT JOIN Branch b ON s.branchno=b.branchno;
ANS:
8 rows
73. Write a SQL query to display all customer names (A_Customers) and their number of Reviews
(A_Reviews). If a customer didn’t give review, his/her number of review will be 0. The output should
have customer name in alphabetic order from A to Z.
ANS:
SELECT c.name, count(r.c_id) FROM A_Customers c
LEFT JOIN A_Reviews r on r.c_id= c.id group by c.id order by c.name ASC;

SET (UNION, INTERSECT, EXCEPT):


74. Construct a list of all cities where there is either a branch office or a property.
ANS:
(SELECT city FROM Branch WHERE city IS NOT NULL)
UNION (SELECT city FROM PropertyForRent WHERE city IS NOT NULL);
75. Construct a list of all cities where there is both a branch office and a property.
ANS 1:
(SELECT city FROM Branch) INTERSECT (SELECT city FROM PropertyForRent);
ANS 2:
SELECT DISTINCT b.city FROM Branch b,PropertyForRent p WHERE b.city=p.city;
76. Write a SQL query to find the vendor names not providing any products.
(refer to A_Vendors, A_Products tables)
ANS:
SELECT name FROM A_Vendors where V_Id not in (SELECT V_Id from A_Products);
77. Construct a list of all cities where there is a branch office but no properties.
ANS:
(SELECT city FROM Branch) EXCEPT (SELECT city FROM PropertyForRent);
ANS 2:
SELECT DISTINCT city FROM Branch WHERE city NOT IN (SELECT city FROM PropertyForRent);

INSERT:
78. Insert a new row into the Staff table supplying data for all columns.
ANS:
INSERT INTO Staff VALUES
('SG16', 'Alan', 'Brown', 'Assistant', 'M', DATE '1957-05-25', 8300, 'B003');
79. Insert a new row into the Staff table supplying data for all mandatory columns: staffNo, fName,
IName, position, salary, and branchNo.
ANS:
INSERT INTO Staff (staffNo, fName, IName, position, salary, branchNo)
VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B003');
ANS 2:
INSERT INTO Staff VALUES ('SG44’, 'Anne’, 'Jones’, 'Assistant’, NULL, NULL, 8100, 'B003’);
80. Assume that there is a table StaffPropCount that contains the names of staff and the number of
properties they manage: StaffPropCount(staffNo, fName, IName, propCount)
Write a SQL to populate the StaffPropCount table using details from the Staff and PropertyForRent
tables.
ANS:
INSERT INTO StaffPropCount (SELECT s.staffNo, fName, IName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo GROUP BY s.staffNo, fName, IName)
UNION
(SELECT staffNo, fName, IName, 0 FROM Staff s
WHERE NOT EXISTS (SELECT * FROM PropertyForRent p WHERE p.staffNo = s.staffNo));

UPDATE:
81. Give all staff a 3% pay increase.
ANS:
UPDATE Staff SET salary = salary*1.03;
82. Give all Managers a 5% pay increase. (Refer to Staff table)
ANS:
UPDATE Staff SET salary = salary*1.05 WHERE position = 'Manager';
83. Promote David Ford (staffNo = ‘SG14’) to Manager and change his salary to $18,000.
(Refer to Staff table)
ANS:
UPDATE Staff SET position = 'Manager', salary = 18000 WHERE staffNo = 'SG14';

DELETE:
84. Delete all viewings that relate to property PG4.
ANS:
DELETE FROM Viewing WHERE propertyNo = 'PG4';
85. Delete all rows from the Viewing table.
ANS:
DELETE FROM Viewing;
86. Delete the record that has the NULL value in QTY field in the A_Sales table
ANS:
DELETE FROM A_Sales WHERE QTY is null;
87. Create the Staff table with proper data type for each field and staffno is the primary key, branchno
is a foreign key reference to the primary key branchno in the Branch table. All the fields cannot be
NULL.
ANS:
CREATE TABLE Staff (staffno varchar(5) not null, fName varchar(15) not null, lName varchar(15) not
null, position varchar(25) not null, Sex char(1) not null, DOB date not null, salary decimal(8,2) not
null, branchno varchar(8) not null, primary key (staffno), foreign key (branchno) references
Branch(branchno));

ALTER:
88. Add a new column TEL varchar(20) to the staff table;
ANS:
ALTER TABLE Staff ADD TEL varchar(25);
89. Change the Staff table by removing the default of ‘Assistant’ for the position column and setting the
default for the sex column to female (‘F’).
ANS:
ALTER TABLE Staff ALTER position DROP DEFAULT;
ALTER TABLE Staff ALTER sex SET DEFAULT 'F';

VIEW:
90. Create a view vTest listing all double or family rooms with a price below 40.00 per night, in
ascending order of price.
ANS:
CREATE VIEW vTest as SELECT * FROM Room
WHERE price < 40 AND type IN ('double', 'family') ORDER BY price asc;
91. Create a view vTest to list the number of rooms in each hotel.
ANS:
SELECT h.hotelname, COUNT(r.roomNo) AS count
FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
92. Create a view vTest to list the hotel name and the total number of rooms with price per room below
40.00 per night.
ANS:
CREATE VIEW vTest as SELECT h.hotelname,count(*) FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno and r.price < 40 group by h.hotelno;
93. Create a view so that the manager at branch B003 can see the details only for staff who work in his
or her branch office.
ANS:
CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchNo = 'B003';
94. Create a view of the staff details at branch B003 that excludes salary information, so that only
managers can access the salary details for staff who work at their branch.
ANS:
CREATE VIEW Staff3 AS SELECT staffNo, fName, IName, position, sex
FROM Staff WHERE branchNo = 'B003';
95. Create a view vTest to show the first name and the working city for staff who was born after January
first 1960.
ANS:
SELECT fname, city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and birthday > '1960-01-01';
96. Create a view vTest to find the total revenue per night for each hotel and the revenue is higher than
85 dollars. Assume all rooms are booked. Your output needs to show the hotel name and the
amount of revenue.
ANS:
SELECT h.hotelno, SUM(price) as revenue FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno group by h.hotelno having revenue > 85;
97. Create a view of staff who manage properties for rent, which includes the branch number they work
at, their staff number, and the number of properties they manage
ANS:
CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)
AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;

GRANT, REVOKE:
98. Give the user with authorization identifier Manager all privileges on the Staff table.
ANS:
GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION;
99. Give users Personnel and Director the privileges SELECT and UPDATE on column salary of the Staff
table.
ANS:
GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director;
100. Give user xyz from IP ’10.20.30.40’ the privileges SELECT on column salary of the Staff table.
ANS:
GRANT SELECT (salary) ON test TO 'xyz'@'10.20.30.40';
101. Remove user xyz’s SELECT privilege from test the test table.
ANS:
REVOKE SELECT on test from xyz;
102. Remove user xyz’s all privileges from test the test table.
ANS:
REVOKE ALL PRIVILEGES on test from xyz;

DROP:
103. Remove a table Data from the database.
ANS:
DROP TABLE table Data;
104. Remove a view vData from the database.
ANS:
DROP VIEW vData;
105. Remove a stored procedure pTest() from the database.
ANS:
DROP procedure pTest;
106. Remove a stored function fTest() from the database.
ANS:
DROP function fTest;
107. Remove a user xyz from the database.
ANS:
DROP USER xyz;

SQL Syntax and runtime issues:


108. Can the following SQL be run without error?
SELECT staffNo, COUNT(salary) FROM Staff;
Yes, it has no syntax error, but the result is meaningless.
109. Can the following SQL be run without error?
SELECT staffNo FROM Staff where salary=max(salary);
No, this query is illegal because the aggregation function max() cannot be compared directly.
110. Is the following view updatable? CREATE VIEW vTest AS SELECT count(*) as ct FROM Staff;
ANS:
No, because the view is created with an aggregate function count()
111. Is the following view updatable? CREATE VIEW vTest AS SELECT fname, lname as ct FROM
Staff;
ANS:
Yes, because every record in vTest can be traced back to the original record in Staff.
112. Is the following view updatable? CREATE VIEW vTest AS SELECT distinct branchno FROM
Staff;
ANS:
No, because the view is created with the distinct keyword.
113. Is the following view updatable?
CREATE VIEW vTest AS SELECT sex FROM Staff GROUP BY sex;
ANS:
No, because the view is created with GROUP BY.
114. Is the following view updatable?
CREATE VIEW vTest AS SELECT branchno, sum(salary) FROM Staff GROUP BY branchno;
ANS:
No, because the view is created with an aggregate function sum() and GROUP BY.
115. Is the following view updatable?
CREATE VIEW vTest AS SELECT staffno,salary from Staff order by salary;
ANS:
Yes, because every record in vTest can be traced back to the original record in Staff. ORDER BY does
not affect the trace.

VARIABLE, ASSIGNMENTS, COMPARISON:


116. What is the output for the following SQL:
SELECT 2=2,3=2,1=NULL, NULL=NULL, NULL IS NULL;
ANS:
+-----+-----+--------+-----------+--------------+
| 2=2 | 3=2 | 1=NULL | NULL=NULL | NULL is NULL |
+-----+-----+--------+-----------+--------------+
| 1 | 0 | NULL | NULL | 1 |
+-----+-----+--------+-----------+--------------+
117. What is the output for the following SQL:
SELECT @a1:=3, @a2=4, @a3=@a2+1;
ANS:
+--------+-------+-----------+
| @a1:=3 | @a2=4 | @a3=@a2+1 |
+--------+-------+-----------+
| 3 | NULL | NULL |
+--------+-------+-----------+

118. What is the output for the following SQL:


SELECT @a1:=3, @a2:=4, @a3:=@a2+@a1;
ANS:
+--------+--------+--------------+
| @a1:=3 | @a2:=4 | @a3:=@a2+@a1 |
+--------+--------+--------------+
| 3 | 4 | 7 |
+--------+--------+--------------+
119. What is the output for the following SQL:
SELECT null and 1, null and 0, 1 and 0, null or 1, null or 0, 1 or 0, not null;
+------------+------------+---------+-----------+-----------+--------+----------+
| null and 1 | null and 0 | 1 and 0 | null or 1 | null or 0 | 1 or 0 | not null |
+------------+------------+---------+-----------+-----------+--------+----------+
| NULL | 0 | 0 | 1 | NULL | 1 | NULL |
+------------+------------+---------+-----------+-----------+--------+----------+

STORED ROUTINES:
120. Write the SQL statement to run a stored function named fMaxSalary()which will return the
staff’s highest salary.
ANS:
SELECT fMaxSalary();
121. Write a stored function named fMaxSalary() which will return the staff’s highest salary.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary() RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff;
RETURN maxSalary ;
END $$
DELIMITER ;
122. Write a stored function named fMaxSalary(bno) which will return the staff’s highest salary
for a given branch no bno.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(bno varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE branchno=bno;
RETURN maxSalary ;
END $$
DELIMITER ;
123. Write a stored function named fMaxSalary(n) which will return the staff’s highest salary for a
given input that is a partial string in the first name field.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(n varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE fname like concat('%',n,'%');
RETURN maxSalary ;
END $$
DELIMITER ;
124. Write the SQL statement to run a stored procedure named pGetNames()which will display the
Staff’s first name and last name who work at branch located at a given city ‘London’.
ANS: call pGetNames('London');
125. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity.
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END $$
DELIMITER ;
126. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity. If the bcity is empty ‘’, please print a message saying
“The input city cannot be empty.”
call pGetNames(''); call pGetNames('London');
+-----------------------------+ +-------+-------+
| message | | fname | lname |
+-----------------------------+ +-------+-------+
| Input city cannot be empty. | | John | White |
+-----------------------------+ | Julie | Lee |
+-------+-------+
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
if (bcity='') THEN
SELECT 'Input city cannot be empty.' as message;
ELSE
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END IF;
END $$
DELIMITER ;
Table of Contents

What is API? 4

What is API Testing? 6

What is REST API? 6

Difference between REST API vs SOAP API. 8

What to Test in API Testing? 8

HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10

HTTP Methods explained. 12


HTTP GET Method Explained - 12
HTTP POST Method Explained - 13
HTTP PUT Method Explained - 13
HTTP PATCH Method Explained - 14
HTTP DELETE & OPTIONS Method Explained - 14
HTTP HEAD/TRACE Method Explained - 15

How to Test an API ( API Testing)? 15

API Testing tools 16

How to do API Testing using Postman 16


What is API?

API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.

For example, It like a connector as seen in the picture. All data connects to our organization through API.

In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.

API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API

Type of APIs :-
What is API Testing?

When we talk about API Testing,

API testing is testing that APIs and its integration with the services.

It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..

In this definite guide,


We are basically discussing about the REST API Testing.Where we need to test the REST APIs for the
validation, error codes and load testing.

What is REST API?


As REST is an acronym for REpresentational State Transfer, statelessness is key. An API can be REST if it
follows the below constraints.

The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.

1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand

Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,

First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.

Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..

Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.

Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.

Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.

Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.

If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).

SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.

Enough of background lets come to topic…

What to Test in API Testing?

● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.

Lets understand why API Testing is important…


Why you should perform API Testing?
● Many of the services that we use every day rely on hundreds of different interconnected APIs, if any
one of them fails then the service will not work.

● Right now, Internet uses millions of APIs and they should be tested thoroughly.

● Developers make mistake and they create buggy APIs..

● Validation of APIs is very important which are going live to production.

Above image shows the architecture of an application and notice that API Testing is important part..

Now…

Lets learn one more concept HTTP Methods

HTTP - Fundamentals

HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.

HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.

What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.

GET /spec.html HTTP/1.1


Host: www.example.org
Cookie: theme=light; sessionToken=abc123

Record the user's browsing activity.


Which pages were visited in the past.
Contain the name of the domain & Lifetime.

Tool : EditThisCookie - http://bit.ly/1oe1o08

What is Authentication and its types lets understand it...

What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.

Basic authentication - String is encoded with Base64.


curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com
Digest Authentication - Authentication is performed by transmitting the password in an ENCRYPTED
form.(With Some Salt etc)

OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.

E.g OAuth 1, 2.

More authentication are discussed here -


https://scrolltest.com/2018/11/22/how-to-handle-authentications-with-postman/

In Client as Browser and Server as DB with the service running in PHP.

We can create an HTTP request from browser by typing a URL.

Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL

Lets Understand what all HTTP methods are present


HTTP Methods explained.

HTTP GET Method Explained -

.
HTTP POST Method Explained -

HTTP PUT Method Explained -


HTTP PATCH Method Explained -

HTTP DELETE & OPTIONS Method Explained -


HTTP HEAD/TRACE Method Explained -

Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.

How to Test an API ( API Testing)?

Before that take a look into the example api that can available freely.

https://api.chucknorris.io/jokes/random

Here Keys are


cateroy, icon_url, id, url and value and they have corresponding values as String or number.
API Testing can be done manually or using a Tools. It is always recommend to certain tools.

Lets learn API Testing using our favorite tools..


Below is the list of API testing tools, You can learn or use whichever tool you feel is great for you, I encourage
you to start with Postman it's an awesome API Testing tool which provide lots of feature like command line,
CI/CD and monitoring of APIs with testcase support.

API Testing tools

● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD

API Testing using POSTMAN


What is Postman?

First of all, let’s understand what is Postman.

It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.

You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.

Its available in the MacOS, Windows and Linux as Native app.

Download Postman - https://www.getpostman.com


Major features of postman
Table of Contents

What is API? 4

What is API Testing? 6

What is REST API? 6

Difference between REST API vs SOAP API. 8

What to Test in API Testing? 8

HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10

HTTP Methods explained. 12


HTTP GET Method Explained - 12
HTTP POST Method Explained - 13
HTTP PUT Method Explained - 13
HTTP PATCH Method Explained - 14
HTTP DELETE & OPTIONS Method Explained - 14
HTTP HEAD/TRACE Method Explained - 15

How to Test an API ( API Testing)? 15

API Testing tools 16

How to do API Testing using Postman 16


What is API?

API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.

For example, It like a connector as seen in the picture. All data connects to our organization through API.

In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.

API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API

Type of APIs :-
What is API Testing?

When we talk about API Testing,

API testing is testing that APIs and its integration with the services.

It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..

In this definite guide,


We are basically discussing about the REST API Testing.Where we need to test the REST APIs for the
validation, error codes and load testing.

What is REST API?


As REST is an acronym for REpresentational State Transfer, statelessness is key. An API can be REST if it
follows the below constraints.

The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.

1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand

Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,

First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.

Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..

Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.

Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.

Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.

Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.

If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).

SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.

Enough of background lets come to topic…

What to Test in API Testing?

● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.

Lets understand why API Testing is important…


Why you should perform API Testing?
● Many of the services that we use every day rely on hundreds of different interconnected APIs, if any
one of them fails then the service will not work.

● Right now, Internet uses millions of APIs and they should be tested thoroughly.

● Developers make mistake and they create buggy APIs..

● Validation of APIs is very important which are going live to production.

Above image shows the architecture of an application and notice that API Testing is important part..

Now…

Lets learn one more concept HTTP Methods

HTTP - Fundamentals

HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.

HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.

What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.

GET /spec.html HTTP/1.1


Host: www.example.org
Cookie: theme=light; sessionToken=abc123

Record the user's browsing activity.


Which pages were visited in the past.
Contain the name of the domain & Lifetime.

Tool : EditThisCookie - http://bit.ly/1oe1o08

What is Authentication and its types lets understand it...

What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.

Basic authentication - String is encoded with Base64.


curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com
Digest Authentication - Authentication is performed by transmitting the password in an ENCRYPTED
form.(With Some Salt etc)

OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.

E.g OAuth 1, 2.

More authentication are discussed here -


https://scrolltest.com/2018/11/22/how-to-handle-authentications-with-postman/

In Client as Browser and Server as DB with the service running in PHP.

We can create an HTTP request from browser by typing a URL.

Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL

Lets Understand what all HTTP methods are present


HTTP Methods explained.

HTTP GET Method Explained -

.
HTTP POST Method Explained -

HTTP PUT Method Explained -


HTTP PATCH Method Explained -

HTTP DELETE & OPTIONS Method Explained -


HTTP HEAD/TRACE Method Explained -

Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.

How to Test an API ( API Testing)?

Before that take a look into the example api that can available freely.

https://api.chucknorris.io/jokes/random

Here Keys are


cateroy, icon_url, id, url and value and they have corresponding values as String or number.
API Testing can be done manually or using a Tools. It is always recommend to certain tools.

Lets learn API Testing using our favorite tools..


Below is the list of API testing tools, You can learn or use whichever tool you feel is great for you, I encourage
you to start with Postman it's an awesome API Testing tool which provide lots of feature like command line,
CI/CD and monitoring of APIs with testcase support.

API Testing tools

● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD

API Testing using POSTMAN


What is Postman?

First of all, let’s understand what is Postman.

It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.

You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.

Its available in the MacOS, Windows and Linux as Native app.

Download Postman - https://www.getpostman.com


Major features of postman
I originally created this Document for all Fresh Graduates and Experience Professional candidates for
Interview Preparation.

* But I have decided to open-source it and make it available for everyone who wants to learn SQA
Fundamental, Database Concepts, SCRUM Fundamentals, OOP Basics, Automation concepts like
selenium, JMeter, and API.

I added everything that you will need as an SQA Engineer Manual or Automation. The ideal use case of
this document is that you print it and keep it next to you while you are learning and practicing on your
computer.

Please approach me if you see any mistake or feel any wrong concept.

If anyone wants to get Training on Manual or Automation tools just ping me on my contact.

Enjoy! Cheers,

MUHAMMAD UMAR ARSHAD CONTACT


Software Quality Assurance Engineer [email protected]
Consultant Automation Engineer
Systems Ltd Pakistan | Visionet USA +92-307-2980604

umar.it.376@outlook
[email protected]
www.linkedin.com/in/muhammad-
umar-arshad-005ba3139

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


1
Table of Contents
Chapter 1 Software Development Life Cycle (SDLC) ................................................................................... 3
Chapter 2 STLC & Principle of Software Testing .......................................................................................... 7
Chapter 3 Testing Documents .................................................................................................................... 10
Chapter 4 Methods & Types of Software Testing ..................................................................................... 18
Chapter 5 Techniques of Software Testing................................................................................................ 30
Chapter 6 Some Common Concepts .......................................................................................................... 33
Chapter 7 Road Map for Mobile Application Testing ............................................................................... 36
Chapter 8 Agile Methodology and Concepts ............................................................................................. 38
Chapter 9 Database & SQL Concepts ......................................................................................................... 44
Chapter 10 Common SQL Queries ............................................................................................................. 60
Chapter 11 Application Program Interface (API)....................................................................................... 61
Chapter 12 Object Oriented Programming Basics (OOP) .......................................................................... 71
Chapter 13 Selenium WebDriver (Automation) ........................................................................................ 73
Chapter 14 JMeter Concepts (Automation) .............................................................................................. 86
Chapter 15 Aptitude Questions ................................................................................................................. 93

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


2
Chapter 1 Software Development Life Cycle (SDLC)

1 What is SDLC? Imp


The Software Development Lifecycle is a systematic process for building software that ensures
the quality and correctness of the software built. SDLC process aims to produce high-quality
software which meets customer expectations. The software development should be complete
in the pre-defined time frame and cost.

2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.

• It offers a basis for project planning, scheduling, and estimating


• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead

3 SDLC Phases? imp


The entire SDLC process divided into the following stages:

• Phase 1: Requirement collection and analysis


• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


3
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).

3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also helps in defining overall system
architecture.
In this phase the QA Engineers comes up with the Test strategy, where they mention
what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing are also done.

3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use.
As soon as the product is given to the customers, they will first do the beta testing/User
Acceptance Testing. If any changes are required or if any bugs are caught, then they will
report it to the engineering team. Once those changes are made or the bugs are fixed
then the final deployment will happen.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


4
Popular SDLC models

Here, are some most important phases of SDLC life cycle:

4 Waterfall model
Waterfall model works well for smaller projects where requirements are very well
understood.
The waterfall is a widely accepted SDLC model. In this approach, the whole process of the
software development is divided into various phases. In this SDLC model, the outcome of one
phase acts as the input for the next phase.

This SDLC model is documentation-intensive, with earlier phases documenting what need be
performed in the subsequent phases.

5 Incremental Model
The incremental model is not a separate model. It is essentially a series of waterfall cycles. The
requirements are divided into groups at the start of the project. For each group, the SDLC
model is followed to develop software. The SDLC process is repeated, with each release adding
more functionality until all requirements are met. In this method, every cycle act as the
maintenance phase for the previous software release. Modification to the incremental model
allows development cycles to overlap. After that subsequent cycle may begin before the
previous cycle is complete.

6 V-Model
In this type of SDLC model testing and the development, the phase is planned in parallel. So,
there are verification phases on the side and the validation phase on the other side. V-Model
joins by Coding phase.

7 Agile Model - imp

Agile methodology is a practice which promotes continue interaction of development and


testing during the SDLC process of any project. In the Agile method, the entire project is
divided into small incremental builds. All of these builds are provided in iterations, and each
iteration lasts from one to three weeks. In ‘Agile Model’ after every sprint there is a demo-
able feature to the customer. Hence customer can see the features whether they are satisfying

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


5
their need or not. Each release is thoroughly tested to ensure software quality is maintained. It is
used for time critical applications.

8 Spiral Model
The spiral model is a risk-driven process model. This SDLC model helps the team to adopt
elements of one or more process models like a waterfall, incremental, waterfall, etc.

This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.

9 Prototyping Model

Prototyping model is a software development model in which prototype is built, tested,


and reworked until an acceptable prototype is achieved. It also creates base to produce the
final system or software. It works best in scenarios where the project's requirements are
not known in detail. It is an iterative, trial and error method which takes place between
developer and client.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


6
Chapter 2 STLC & Principle of Software Testing

1 What is Software Testing? imp


According to ANSI/IEEE 1059 standard – A process of analyzing a software item to detect
the differences between existing and required conditions (i.e., defects) and to evaluate the
features of the software item.

2 What are the principles of software testing?

2.1 Testing shows presence of defects

Software Testing reduces the probability of undiscovered defects remaining in the


software but even if no defects are found, it is not a proof of correctness.

2.2 Exhaustive testing is impossible

If you were testing this Operating system, you would realize that defects are likely to be
found in multi-tasking activity and need to be tested thoroughly which brings us to our
next principal Defect Clustering.

2.3 Early testing

Early Testing - Testing should start as early as possible in the Software Development Life
Cycle. So that any defects in the requirements or design phase are captured in early
stages.

2.4 Defect clustering

Defect Clustering which states that a small number of modules contain most of the
defects detected. If the same tests are repeated over and over again, eventually the
same test cases will no longer find new bugs.

2.5 Pesticide Paradox

Repetitive use of the same pesticide mix to eradicate insects during farming will over
time lead to the insects developing resistance to the pesticide Thereby ineffective of
pesticides on insects. The same applies to software testing. If the same set of repetitive
tests are conducted, the method will be useless for discovering new defects. To
overcome this, the test cases need to be regularly reviewed & revised, adding new &
different test cases to help find more defects.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
7
2.6 Testing is context depending

Testing is context dependent which basically means that the way you test an e-
commerce site will be different from the way you test a commercial off the shelf
application. All the developed software’s are not identical. You might use a different
approach, methodologies, techniques, and types of testing depending upon the
application type.

2.7 Absence of error - Fallacy

It is possible that software which is 99% bug-free is still unusable. This can be the case if
the system is tested thoroughly for the wrong requirement. The absence of Error is a
Fallacy i.e. Finding and fixing defects does not help if the system build is unusable and
does not fulfill the user's needs & requirements.

3 What is STLC? imp


It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.

Following steps are involved in Software Testing Life Cycle (STLC).

1. Requirement Analysis (RTM)


2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting

4 What are Quality Assurance and Quality Control? imp


Quality Assurance:

Quality Assurance involves in process-oriented activities. It ensures the prevention of


defects in the process used to make Software Applications. So the defects don’t arise when
the Software Application is being developed. The process is:

• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


8
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.

Quality Control:

Quality Control involves in product-oriented activities. It executes the program or code to


identify the defects in the Software Application.

5 What are the Quality assurance and Quality Control standards?


Quality assurance system standards, including ISO 9001, are defined as frameworks that
provide regulations to organizations to ensure that their processes, inputs, products, and
services are capable of meeting every customer requirement.

• Ensuring maximum satisfaction of clients by meeting their quality requirements


• Safety of products and services during usage
• Complying with international regulations and local legislative rules
• Being environmentally responsible
• Confidentiality of stakeholders including customers, employees, partners, and investors
• Assuring a safer workplace for employees
• Optimum allocation of resources and minimization of waste

6 What is Verification & Validation in software testing? imp

• Validation: Are we building the right system?


• Verification: Are we building the system, right?
In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.

While verification is concerned with whether the system is well-engineered, error-free,


and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


9
Chapter 3 Testing Documents
1. What is Test Plan Document?
Test plan document is a document which contains the plan for all the testing activities to be
done to deliver a quality product. Test Plan document is derived from the Product
Description, SRS, or Use Case documents for all future activities of the project. It is usually
prepared by the Test Lead or Test Manager.

1. Test plan identifier


2. References
3. Introduction
4. Test items (functions)
5. Software risk issues
6. Features to be tested
7. Features not to be tested
8. Approach
9. Items pass/fail criteria
10. Suspension criteria and resolution requirements
11. Test deliverables
12. Remaining test tasks
13. Environmental needs
14. Staff and training needs
15. Responsibility
16. Schedule
17. Plan risks and contingencies
18. Approvals

2. What is Test Strategy? imp


Test Strategy is a high-level document (static document) and usually developed by the
project manager. It is a document that captures the approach on how we go about testing
the product achieving the goals. It is normally derived from the Business Requirement
Specification (BRS). Documents like Test strategy doc is project-based document it can
change according to project domain and requirements.

3. What is Test Suite? imp


Test Suite is a collection of test cases. The test cases which are intended to test an
application.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


10
4. What is Test Scenario? imp
Test Scenario gives the idea of what we have to test. Test Scenario is like a high-level test
case. A test scenario is more agile and focuses on the end-to-end functionality of the software.

5. What is Test Case? imp

Test cases are the set of positive and negative executable steps of a test scenario, A test
case is a set of actions performed on a system to determine if it satisfies software
requirements and functions correctly.

Components of Test case:


• Test suite ID (Mandatory)
• Test case ID (Mandatory)
• Summary / Objective (Mandatory)
• Steps to be executed (Mandatory)
• Test Data (Mandatory)
• Pre-Conditions (Non-Mandatory)
• Post-Conditions (Non-Mandatory)
• Expected Result (Mandatory)
• Actual Result (Mandatory)
• Comments/Remarks (Non-Mandatory)
• Status – pass/fail (Mandatory)

6. What is Test Bed? imp

An environment configured for testing. Test bed consists of hardware, software, network
configuration, an application under test, other related software.

7. What is Test Environment? imp

Test Environment is the combination of hardware and software on which Test Team
performs testing. Example:

• Application Type: Web Application


• OS: Windows
• Web Server: IIS
• Web Page Design: Dot Net
• Client-Side Validation: JavaScript
• Server-Side Scripting: ASP Dot Net
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
11
• Database: MS SQL Server
• Browser: IE/Firefox/Chrome

8. What is Test Data?

Test data is the data that is used by the testers to run the test cases. Whilst running the test
cases, testers need to enter some input data. To do so, testers prepare test data. It can be
prepared manually and also by using tools.

9. What is Test Harness? imp

Test Harness in Software Testing is a collection of stubs, drivers and other supporting tools
required to automate test execution. Test harness executes tests by using a test library and
generates test reports. Test harness contains all the information needed to compile and run
a test like test cases, target deployment port (TDP), source file under test, stubs, etc.

10. What is Test Closure?

Test Closure is the note prepared before test team formally completes the testing process.
This note contains the total no. of test cases, total no. of test cases executed, total no. of
defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected
etc.,

11. What is Risk Factor and its Types?

In software testing Risks are the possible problems that might endanger the objectives of
the project stakeholders. It is the possibility of a negative or undesirable outcome. A risk is
something that has not happened yet and it may never happen; it is a potential problem.

The types of Risk in a Test Project can be broadly categorized as

1. Strategy Risk: This includes Budget, Communication and Management risks


2. Project Definition Risks: This includes Project target, Scope, and requirements risks.
3. Human Resources Risk: This includes Skill, Team members and organization risks.

12. What are the tasks of Test Closure activities in Software Testing?

Test Closure activities fall into four major groups.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


12
Test Completion Check: To ensure all tests should be either run or deliberately skipped
and all known defects should be either fixed, deferred for a future release or accepted as a
permanent restriction.

Test Artifacts handover: Tests and test environments should be handed over to those
responsible for maintenance testing. Known defects accepted or deferred should be
documented and communicated to those who will use and support the use of the system.

Lessons learned: Analyzing lessons learned to determine changes needed for future
releases and projects. In retrospective meetings, plans are established to ensure that good
practices can be repeated and poor practices are not repeated.

Result: Archiving results, logs, reports, and other documents and work products in the
CMS (configuration management system).

13. List out Test Deliverables?

1. Test Strategy
2. Test Plan
3. Effort Estimation Report
4. Test Scenarios
5. Test Cases/Scripts
6. Test Data
7. Requirement Traceability Matrix (RTM)
8. Defect Report/Bug Report
9. Test Execution Report
10. Graphs and Metrics
11. Test summary report
12. Test incident report
13. Test closure report
14. Release Note
15. Installation/configuration guide
16. User guide
17. Test status report
18. Weekly status report (Project manager to client)

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


13
14. What is RTM? imp

Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.

Which Parameters to include in Requirement Traceability Matrix?

• Requirement ID
• Requirement Type and Description
• Test Cases with Status

Types of Traceability Test Matrix

In Software Engineering, traceability matrix can be divided into three major components as
mentioned below:

• Forward traceability: This matrix is used to check whether the project progresses in the
forward desired direction and for the right product. It maps requirements to test cases.
• Backward or reverse traceability: It is used to ensure whether the current product
remains on the right track. It maps test cases to requirements.
• Bi-directional traceability (Forward + Backward): This traceability matrix ensures that all
requirements are covered by test cases. It analyzes the impact of a change in
requirements affected by the Defect in a work product and vice versa.

How to create Requirement Traceability Matrix?


Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
14
On the basis of the Business Requirement Document (BRD) and Technical Requirement
Document (TRD), testers start writing test cases.

Step 1: Our sample Test Case is

"Verify Login, when correct ID and Password is entered, it should log in successfully"

Step 2: Identify the Technical Requirement that this test case is verifying. For our test case, the
technical requirement is T94 is being verified.

Step 3: Note this Technical Requirement (T94) in the Test Case.

Step 4: Identify the Business Requirement for which this TR (Technical Requirement-T94) is
defined

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


15
Step 5: Note the BR (Business Requirement) in Test Case

Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your Test Suite. RTM
in testing is Ready!

Advantage of Requirement Traceability Matrix

• It confirms 100% test coverage


• It highlights any requirements missing or document inconsistencies
• It shows the overall defects or execution status with a focus on business requirements
• It helps in analyzing or estimating the impact on the QA team's work with respect to
revisiting or re-working on the test cases.

15. What is Test Coverage? imp

Test Coverage states which requirements of the customers are to be verified when the
testing phase starts. Test Coverage is a term that determines whether the test cases are
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
16
written and executed to ensure to test the software application completely, in such a
way that minimal or NIL defects are reported.

How to achieve Test Coverage?


The maximum Test Coverage can be achieved by establishing good ‘Requirement
Traceability’.

• Mapping all internal defects to the test cases designed


• Mapping all the Customer Reported Defects (CRD) to individual test cases for the
future regression test suite.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


17
Chapter 4 Methods & Types of Software Testing

There are 3 methods of software testing.

1) White box 2) Black box 3) Grey Box

1. What is White Box Testing? imp

White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on
applications internal code structure. In white-box testing, an internal perspective of the
system, as well as programming skills, are used to design test cases. This testing usually was
done at the unit level.

2. What is Black Box Testing? imp

Black Box Testing is a software testing method in which testers evaluate the functionality of the
software under test without looking at the internal code structure. This can be applied to every
level of software testing such as Unit, Integration, System and Acceptance Testing.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
18
3. What is Grey Box Testing?

Grey box is the combination of both White Box and Black Box Testing. The tester who works on
this type of testing needs to have access to design documents. This helps to create better test
cases in this process.

There are 3 Types of Software testing (Alpha, Beta, Gamma)

4. What is Alpha Testing? imp

Alpha testing is done by the in-house developers (who developed the software) and testers.
Sometimes alpha testing is done by the client or outsourcing team with the presence of
developers or testers.

It has two phases:

• In the first phase of alpha testing, the software is tested by in-house developers. They
use debugger software. The goal is to catch bugs quickly.
• In the second phase of alpha testing, the software is handed over to the software QA
staff, for additional testing in an environment that is similar to the intended use.

5. What is Beta Testing? imp

Beta testing is done by a limited number of end users before delivery. Usually, it is done in
the client place.

6. What is Gamma Testing?

Gamma testing is done when the software is ready for release with specified requirements.
It is done at the client place. It is done directly by skipping all the in-house testing activities.

7. What is Functional Testing? imp

In simple words, what the system actually does is functional testing. To verify that each
function of the software application behaves as specified in the requirement document.
Testing all the functionalities by providing appropriate input to verify whether the actual
output is matching the expected output or not. It falls within the scope of black box testing
and the testers need not concern about the source code of the application.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


19
7.1 What is Unit/Module Testing? imp

Unit Testing is also called as Module Testing or Component Testing. It is done to check
whether the individual unit or module of the source code is working properly. It is done
by the developers in the developer’s environment.

7.2 What is Integration Testing? imp

Integration Testing is the process of testing the interface between the two software
units. Integration testing is done by three ways. Big Bang Approach, Top-Down
Approach, Bottom-Up Approach.

7.3 What is System Testing? imp

Testing the fully integrated application to evaluate the system’s compliance with its
specified requirements is called System Testing End to End testing. Verifying the
completed system to ensure that the application works as intended or not.

System testing is carried out by specialist testers or independent testers.


System testing should investigate both functional and non-functional requirements of
the testing.

7.4 What is Smoke Testing? imp

Smoke Testing is done to make sure if the build we received from the development
team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It
helps not to waste the testing time to simply testing the whole application when the key
features don’t work or the key bugs have not been fixed yet.

7.5 What is Sanity Testing? imp

Sanity Testing is done during the release phase to check for the main functionalities of
the application without going deeper. It is also called as a subset of Regression testing. It
is done at the “release level”. We perform sanity testing when we don’t have enough
time for regression testing.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


20
7.6 What is Regression Testing? imp

Repeated testing of an already tested program, after modification, to discover any


defects introduced or uncovered as a result of the changes in the software being tested
or in another related or unrelated software components.

Usually, we do regression testing in the following cases:

1. New functionalities are added to the application


2. Change Requirement (In organizations, we call it as CR)
3. Defect Fixing
4. Performance Issue Fix
5. Environment change (E.g., Updating the DB from MySQL to Oracle)

7.7 What is Retesting Testing? imp

Retesting is done to make sure that the tests cases which failed in last execution are
passed after the defects are fixed. Retesting is carried out based on the defect fixes. In
Retesting, the cases which are failed earlier can be included to check if the functionality
failure in an earlier build.

7.8 What is Exploratory Testing? Imp

Usually, this process will be carried out by domain experts. They perform testing just by
exploring the functionalities of the application without having the knowledge of the
requirements.

8. What is Monkey Testing?

Perform abnormal action on the application deliberately in order to verify the stability of
the application.

9. What is Big Bang Approach?

Combining all the modules once and verifying the functionality after completion of
individual module testing.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


21
Top down and bottom up are carried out by using dummy modules known as Stubs and
Drivers. These Stubs and Drivers are used to stand-in for missing components to simulate
data communication between modules.

10. What is Top-Down Approach?

Testing takes place from top to bottom. High-level modules are tested first and then low-
level modules and finally integrating the low-level modules to a high level to ensure the
system is working as intended. Stubs are used as a temporary module if a module is not
ready for integration testing.

11. What is Bottom-Up Approach?

It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up.
Lowest level modules are tested first and then high-level modules and finally integrating the
high-level modules to a low level to ensure the system is working as intended. Drivers are
used as a temporary module for integration testing.

12. What is User Acceptance Testing / UAT? imp

It is also known as pre-production testing. This is done by the end users along with the
testers to validate the functionality of the application. After successful acceptance
testing. Formal testing conducted to determine whether an application is developed as per
the requirement. It allows the customer to accept or reject the application. Types of
acceptance testing are Alpha, Beta & Gamma.

13. What is Positive and Negative Testing?

Positive Testing: It is to determine what system supposed to do. It helps to check


whether the application is justifying the requirements or not.

Negative Testing: It is to determine what system not supposed to do. It helps to find
the defects from the software.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


22
14. What is Non-Functional Testing? imp

In simple words, how well the system performs is non-functionality testing. Non-
functional testing refers to various aspects of the software such as performance, load,
stress, scalability, security, compatibility etc., Main focus is to improve the user
experience on how fast the system responds to a request.

15.1. What is Performance Testing? imp

This type of testing determines or validates the speed, scalability, and/or stability
characteristics of the system or application under test. Performance is concerned with
achieving response times, throughput, and resource-utilization levels that meet the
performance objectives for the project or product.

15.2. What is Load Testing? imp

It is to verify that the system/application can handle the expected number of


transactions and to verify the system/application behavior under both normal and peak
load conditions.

15.3. What is Volume Testing? imp

It is to verify that the system/application can handle a large amount of data.

15.4. What is Stress Testing? imp

It is to verify the behavior of the system once the load increases more than its design
expectations.

15.5. What is Scalability Testing?

Scalability testing is a type of non-functional testing. It is to determine how the


application under test scales with increasing workload.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


23
15.6. What is Concurrency Testing?

Concurrency testing means accessing the application at the same time by multiple users
to ensure the stability of the system. This is mainly used to identify deadlock issues.

15.7. What is GUI Testing? imp

Graphical User Interface Testing is to test the interface between the application and the
end user.

15.8. What is Recovery Testing?

Recovery testing is performed in order to determine how quickly the system can recover
after the system crash or hardware failure. It comes under the type of non-functional
testing.

15.9. What is Installation Testing?

It is to check whether the application is successfully installed and it is working as


expected after installation.

15.10. What is Formal Testing? Imp

It is a process where the testers test the application by having pre-planned


procedures and proper documentation.

15.11. What is Risk Based Testing? imp

Identify the modules or functionalities which are most likely cause failures and then
testing those functionalities.

15.12. What is Compatibility Testing?

It is to deploy and check whether the application is working as expected in a different


combination of environmental components.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


24
15.13. What is Usability Testing?

To verify whether the application is user-friendly or not and was comfortably used by an
end user or not. The main focus in this testing is to check whether the end user can
understand and operate the application easily or not. An application should be self-
exploratory and must not require training to operate it.

15.14. What is Security Testing? imp

Security testing is a process to determine whether the system protects data and
maintains functionality as intended.

16. What is Soak Testing? imp

Running a system at high load for a prolonged period of time to identify the
performance problems is called Soak or Endurance Testing.

17. What is Fuzz Testing? Imp

Fuzz testing is used to identify coding errors and security loopholes in an application. By
inputting massive amount of random data to the system in an attempt to make it crash
to identify if anything breaks in the application.

18. What is Adhoc Testing? imp

Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In
Adhoc testing, testers randomly test the application without following any documents
and test design techniques. This testing is primarily performed if the knowledge of
testers in the application under test is very high. Testers randomly test the application
without any test cases or any business requirement document.

19. What is Interface Testing?

Interface testing is performed to evaluate whether two intended modules pass data and
communicate correctly to one another.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


25
19.1. What is Reliability Testing?

Perform testing on the application continuously for long period of time in order to verify
the stability of the application.

20. What is Bucket Testing? imp

Bucket or Split testing is a method to compare two versions of an application against


each other to determine which one performs better.

21. What is Defect Cascading in Software Testing?

Defect cascading in Software testing means triggering of other defects in an application.


When a defect is not identified or goes unnoticed while testing, it invokes other defects.
It leads to multiple defects in the later stages and results in an increase in a number of
defects in the application.

For example, if there is a defect in an accounting system related to negative taxation


then the negative taxation defect affects the ledger which in turn affects other reports
such as Balance Sheet, Profit & Loss etc.,

22. What is Walk Through? imp

A walkthrough is an informal meeting conducts to learn, gain understanding, and find


defects. The author leads the meeting and clarifies the queries raised by the peers in the
meeting.

23. What is Inspection? imp

Inspection is a formal meeting lead by a trained moderator, certainly not by the author.
The document under inspection is prepared and checked thoroughly by the reviewers
before the meeting. In the inspection meeting, the defects found are logged and shared
with the author for appropriate actions. Post inspection, a formal follow-up process is
used to ensure a timely and corrective action.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


26
24. Who are all involved in an inspection meeting?

Author, Moderator, Reviewer(s), Scribe/Recorder and Manager.

25. What is a Defect? imp

The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.

26. What is a Bug? imp

If testers find any mismatch in the application/system in testing phase, then they call it
as Bug.

27. What is an Error? imp

We can’t compile or run a program due to a coding mistake in a program. If a developer


unable to successfully compile or run a program, then they call it as an error.

28. What is a Failure? imp

Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.

29. What is Bug Severity? imp

Bug/Defect severity can be defined as the impact of the bug on customer’s business. It
can be Critical, Major or Minor. In simple words, how much effect will be there on the
system because of a particular defect.

30. What is Bug Priority? imp

Defect priority can be defined as how soon the defect should be fixed. It gives the order
in which a defect should be resolved. Developers decide which defect they should take

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


27
up next based on the priority. It can be High, Medium or Low. Most of the times the
priority status is set based on the customer requirement.

Tell some examples of Bug Severity and Bug Priority? Imp

High Priority & High Severity: Submit button is not working on a login page and
customers are unable to login to the application

Low Priority & High Severity: key feature failed but there’s no impact on customer
business, e.g., calculation fault in yearly report which end user won’t use on daily basis.

High Priority & Low Severity: Spelling mistake of a company name on the homepage

Low Priority & Low Severity: FAQ page takes a long time to load

31. What is a Critical Bug?

A critical bug is a show stopper which means a large piece of functionality or major
system component is completely broken and there is no workaround to move further.
For example, Due to a bug in one module, we cannot test the other modules because
that blocker bug has blocked other modules. Bugs which affect the customers’ business
are considered as critical.

Example:

1. “Sign In” button is not working on Gmail App and Gmail users are blocked to login to
their accounts.
2. An error message pops up when a customer clicks on transfer money button in a
Banking website.

32. What are entry criteria?

Entry criteria is a set of conditions that permits a task to perform, or in absence of any of
these conditions, the task cannot be performed.

• The requirement document should be available.


• Complete understanding of the application flow is required.
• The Test Plan Document should be ready.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


28
33. What is exit criteria?
Exit criteria is a set of expectations; this should be met before concluding the STLC
phase.

• Test Cases should be written and reviewed.


• Test Data should be identified and ready.
• Test automation script should be ready if applicable.

34. What is the Test Management Reviews & Audit?

• Management Review:

Management Review is also known as Software Quality Assurance or (SQA). It focuses


more on the software process rather than the software work products. Quality
Assurance is a set of activities designed to ensure that the project manager follows the
standard process which is already pre-defined. In other words, Quality Assurance makes
sure the Test Manager is doing the right things in the right way.

• Audit:

An audit is the examination of the work products and related information to assesses
whether the standard process was followed or not.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


29
Chapter 5 Techniques of Software Testing

5.1. What is Boundary Value Analysis? imp

Boundary value analysis (BVA) is based on testing the boundary values of valid and invalid
partitions. Every partition has its maximum and minimum values and these maximum and
minimum values are the boundary values of a partition.

Example:
Input condition is valid between 1 to 10

Boundary values 0,1,2 and 9,10,11

5.2. What is Decision Table testing? imp

Decision Table is a Cause-Effect Table. This test technique is appropriate for functionalities
which has logical relationships between inputs (if-else logic). In Decision table technique, we
deal with combinations of inputs. To identify the test cases with decision table, we consider
conditions and actions. We take conditions as inputs and actions as outputs.

How to make Decision Table for Upload Screen?

Now consider a dialogue box which will ask the user to upload photo with certain conditions
like –

1. You can upload only '.jpg' format image


2. file size less than 32kb
3. resolution 137*177.

If any of the conditions fails, the system will throw corresponding error message stating the
issue and if all conditions are met photo will be updated successfully.

Let's create the decision table for this case.


Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
30
Conditions Case 1 Case 2 Case 3 Case 4 Case 5 Case 6 Case 7 Case 8

Format .jpg .jpg .jpg .jpg Not .jpg Not .jpg Not .jpg Not .jpg

Size Less Less than >= 32kb >= 32kb Less than Less than >= 32kb >= 32kb
than 32kb 32kb 32kb
32kb

resolution 137*177 Not 137*177 Not 137*177 Not 137*177 Not


137*177 137*177 137*177 137*177

Output Photo Error Error Error Error Error Error


uploaded message message message message message message
resolution size size and for format format for format
mismatch mismatch resolution mismatch and and size
mismatch resolution mismatch
mismatch

5.3. Equivalence Class Partitioning

Equivalence Partitioning or Equivalence Class Partitioning is type of black box testing


technique which can be applied to all levels of software testing like unit, integration,
system, etc. In this technique, input data units are divided into equivalent partitions that
can be used to derive test cases which reduces time required for testing because of small
number of test cases.

• It divides the input data of software into different equivalence data classes.
• You can apply this technique, where there is a range in the input field.

Example 1: Equivalence and Boundary Value

• Let's consider the behavior of Order Pizza Text Box Below


• Pizza values 1 to 10 is considered valid. A success message is shown.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


31
• While value 11 to 99 are considered invalid for order and an error message will
appear, "Only 10 Pizza can be ordered"

Submit
Order Pizza:

Here is the test condition

1. Any Number greater than 10 entered in the Order Pizza field (let say 11) is considered
invalid.
2. Any Number less than 1 that is 0 or below, then it is considered invalid.
3. Numbers 1 to 10 are considered valid
4. Any 3 Digit Number say -100 is invalid.

5.4. What is State Transition?

Using state transition testing, we pick test cases from an application where we need to
test different system transitions. We can apply this when an application gives a different
output for the same input, depending on what has happened in the earlier state.

5.5. Error Guessing

Error Guessing is a software testing technique based on guessing the error which can
prevail in the code. The technique is heavily based on the experience where the test
analysts use their experience to guess the problematic part of the testing application.
Hence, the test analysts must be skilled and experienced for better error guessing.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


32
Chapter 6 Some Common Concepts

6.1. What is the difference between a Standalone application, Client-


Server application and Web application?

Standalone application:

Standalone applications follow one-tier architecture. Presentation, Business, and


Database layer are in one system for a single user.

Client-Server Application:

Client-server applications follow two-tier architecture. Presentation and Business layer


are in a client system and Database layer on another server. It works majorly in Intranet.

Web Application:

Web server applications follow three-tier or n-tier architecture. The presentation layer is
in a client system, a Business layer is in an application server and Database layer is in a
Database server. It works both in Intranet and Internet.

6.2. What are main differences between UI and UX?

UX design refers to the term “user experience design”, while UI stands for “user
interface design”.

There is an analogy I like to use to describe the different parts of a (digital) product:

If you imagine a product as the human body, the bones represent the code which give it
structure.

The organs represent the UX design: measuring and optimizing against input for
supporting life functions. And UI design represents the cosmetics of the body; its
presentation, its senses and reactions.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


33
6.3. Can you do System testing at any stage of SDLC?

We can do System Testing only when all the units are in place and working properly. It
can only be done before User Acceptance Testing (UAT).

6.4. When to stop testing? (Or) How do you decide when you have
tested enough? imp

There are many factors involved in the real-time projects to decide when to stop testing.

1. Testing deadlines or release deadlines


2. By reaching the decided pass percentage of test cases
3. The risk in the project is under acceptable limit
4. All the high priority bugs, blockers are fixed
5. When acceptance criteria are met.

6.5. What information should be included in a Defect or Bug report?

1. A brief summary of the defect


2. A full description of the defect including steps to reproduce
3. Screenshot attachments if required
4. Date the defect was found and raised
5. Who reported the defect?
6. Severity and/or Priority of the defect
7. Which component is the defect assigned?
8. Current status of Bug.

6.6. What are the test case for Glass of Water?

Check-list:
1. look & feel
2. height
3. weight
4. material used
5. radius at top & bottom
6. capacity
7. color
8. grip
9. breakable / unbreakable

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


34
6.7. What are the test case for AC and AC Remote?

Test scenarios for AC

10. Verify the type of AC, if it’s Window AC or Split AC.


11. Verify the cooling capacity of the AC (ton). It should be as per the specifications.
12. Verify that the voltage requirement of the AC is as per the specifications.
13. Check if the AC voltage regulator works correctly or not.
14. Check the time taken by AC to start cooling, since the plug-in.
15. Check if it’s working in every temperature setting.
16. Verify the minimum temperature that can be achieved by the AC.
17. Verify the maximum temperature that can be achieved by the AC.
18. Check if the different AC fan speeds, work correctly.
19. Verify that the information displayed in the display panel is correct.
20. Check if all the keys of the display panel are working.
21. Check if the display isn’t too bright or too dark.
22. Check if the outer body of the AC is sturdy and rugged.
23. Check if the AC works with the remote.
24. Check if all the keys of the panel do the same work as mentioned.
25. Check if the grill is movable in all directions.
26. Verify if the AC switches off and on when reached the desired temperature, for
saving electricity.
27. Check the amount of water leakage.

Test scenarios for AC remote

1. Verify the functionality of the on/off button.


2. Check if all the keys are in perfect condition.
3. Check if the remote belongs to the same AC.
4. Check if the name of the keys is mentioned.
5. Check the response time between the AC remote and the AC.
6. Check if the keys are doing the desired function or not.
7. Verify the durability of the keys and body of the remote.
8. Verify that the remote works each time old batteries are replaced.
9. Check if it’s waterproof if mentioned.
10. Check if too much pressure isn’t required to press the keys.
11. Check if the spacing among the keys is adequate.
12. Check the weight and dimensions of the remote.
13. Check if another function isn’t triggered with any key other than specified.
14. Check if the body of the remote isn’t flimsy.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


35
Chapter 7 Road Map for Mobile Application Testing

What you need and what stages you need to test when you receive the Mobile Application,
there are some major concerns I have listed and you should know.

7.1. Functional testing

Testing is done by certifying the requirements. like whether the application is working
based on the requirements or not.

7.2. Android/IOS UI/Responsiveness testing

This is a user-centric testing of the application. In this test phase, items such as
visibility of text in various screens of the app, interactive messages, alignment of
elements, the look and feel of the app for different screens, size of fields etc. are
tested under this.

Most important point of this testing:


• Device Selection (must prefer Real device always)
• Device emulators are cost effective and they come in handy during the initial
development phase.
• But, to test the real-life scenarios, physical devices are the must. Both emulators
and physical devices are to be used in a balanced manner for an optimized
result.

7.3. Compatibility testing


The extension for Android apps is .APK. and for iOS apps is .ipa should be confirm.
This testing is done mostly in the form of two matrices of OS Vs app and Device
Model Vs App. Usually, a list of supported OS (and sometimes devices) is provided
by the product owner or customer.

7.4. Interface Testing

This testing is done after all the modules of the app are completely developed,
tested individually and all the bugs are fixed verified.

7.5. Network Testing

During this testing, request/response to/from the service is tested for various
conditions.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
36
This test is mainly done to verify the response time in which the activity is performed
like refreshing data after sync or loading data after login etc.

7.6. Performance Testing

Performance of the application under some peculiar conditions are checked.


Those conditions include:
• Low memory in the device.
• The battery in extremely at a low level.
• Poor/Bad network reception.

7.7. Installation/Uninstallation testing

This is to ensure smooth installation and uninstallation of the application without


ending up in errors, partial installation etc.

7.8. Security Testing

Testing of the data flow for encryption and decryption mechanism is to be tested in
this phase. Access to stored data is also tested in this phase.

7.9. Field testing


Field testing is done specifically for the mobile data network and not in-house but by
going out and using the app as a normal user.

It is basically done to verify the behavior of the app when the phone has a 2G or 3G
connection. Field testing verifies if the app is crashing under slow network
connection or if it is taking too long to load the information.

7.10. Interrupt Testing

This is the Offline Scenario Verification. Conditions where the communication breaks
in the middle are called as offline conditions.
Some of the conditions where interruptions of a network can be tested are as
follows:

• Data cable removal during data transfer process.


• Network outage during the transaction posting phase.
• Network recovery after an outage.
• Battery removal or Power On/Off when it is in the transactional phase.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


37
Chapter 8 Agile Methodology and Concepts

8.1. What is Agile Testing?

Agile Testing is a practice that a QA follows in a dynamic environment where testing


requirements keep changing according to customer needs. It is done parallel to the
development activity where the testing team receives frequent small codes from the
development team for testing.

8.2. What is the difference between burn-up and burn-down charts?

Burn-up and burn-down charts are used to keep track of the progress of the project.
Burn-up charts represent how much work has been completed in any project
whereas Burn-down chart represents the remaining work in a project.

8.3. Define the roles in Scrum?

There are mainly three roles that a Scrum team have:


1. Project Owner has the responsibility of managing the product backlog. Works
with end-users and customers and provides proper requirements to the team to
build the proper product.
2. Scrum Master works with the scrum team to make sure each sprint gets
completed on time. Scrum master ensures proper workflow for the team.
3. Scrum Team: Each member of the team should be self-organized, dedicated
and responsible for the high quality of the work.

8.4. What is Product Backlog & Sprint Backlog?

Product backlog is maintained by the project owner which contains every feature
and requirement of the product.
Sprint backlog can be treated as the subset of product backlog which contains
features and requirements related to that particular sprint only.

8.5. Explain Velocity in Agile.

Velocity is a metric that is calculated by the addition of all efforts estimates


associated with user stories completed in an iteration. It predicts how much work
Agile can complete in a sprint and how much time will it require to complete a
project.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


38
8.6. Explain the difference between a traditional Waterfall
model and Agile testing?

Agile testing is done parallel to the development activity whereas a traditional


waterfall model testing is done at the end of the development.
As done in parallel, agile testing is done on small features whereas, in a waterfall
model, testing is performed on the whole application.

8.7. Explain Pair Programming and its benefits?

Pair programming is a technique in which two programmer works as a team in which


one programmer writes code and other one reviews that code. They both can switch
their roles.
Benefits:
• Improved code quality: As the second partner reviews the code
simultaneously, it reduces the chances of mistake.
• Knowledge transfer is easy: One experienced partner can teach another
partner about the techniques and codes.

8.8. What is Re-factoring?

Modification of the code without changing its functionality to improve the


performance is called Re-factoring.

8.9. Explain the Iterative and Incremental Development in Agile?

Iterative Development: Software is developed and delivered to the customer and


based on the feedback again developed in cycles or releases and sprints.
Example: Release 1 software is developed in 5 sprints and delivered to the
customer. Now, the customer wants some changes, then the development team plan
for 2nd release which can be completed in some sprints and so on.
Incremental Development: Software is developed in parts or increments. In each
increment, a portion of the complete requirement is delivered.

8.10. How do you deal when requirements change frequently?

This question is to test the analytical capability of the candidate.


The answer can be: Work with PO to understand the exact requirement to update
test cases. Also, understand the risk of changing the requirement. Apart from this,
one should be able to write a generic test plan and test cases. Don’t go for the
automation until requirements are finalized.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


39
8.11. What is a test stub?

Test stub is a small code that mimics(copy) a specific component in the system and
can replace it. Its output is the same as the component it replaces.

8.12. What qualities should a good Agile tester have?

• He should be able to understand the requirements quickly.


• He should know Agile concepts and principals.
• As requirements keep changing, he should understand the risk involved in it.
• The agile tester should be able to prioritize the work based on the requirements.
• Communication is a must for an Agile tester as it requires a lot of communication
with developers and business associates.

8.13. What is the difference between Epic, User stories & Tasks?

User Stories: It defines the actual business requirement. Generally created by the
business owner.
Task: To accomplish the business requirements development team create tasks.
Epic: A group of related user stories is called an Epic.

8.14. What is a Task board in Agile?

Task board is a dashboard that shows the progress of the project.


It contains:
• User Story: It has the actual business requirement, which consist of User
Acceptance Criteria(UAC).
• To Do: Tasks that can be worked on.
• In Progress: Tasks in progress.
• To Verify: Tasks pending for verification or testing
• Done: Completed tasks.

8.15. What is Test Driven Development (TDD)?

It is a Test-first development technique in which we add a test first before we write


the complete production code. Next, we run the test and based on the result refactor
the code to fulfill the test requirement.

8.16. How QA can add value to an agile team?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


40
QA can provide value addition by think outside the box about the various scenarios
to test a story. They can provide quick feedback to the developers about whether
new functionality is working fine or not.

8.17. What is Scrum ban?

It is a software development model that is a combination of Scrum and Kanban.


Scrum ban is considered for maintaining projects in which there are frequent
changes or unexpected user stories. It can reduce the minimum completion time for
user stories.

8.18. What is the Application Binary Interface?

Application Binary Interface or ABI is defined as an interface for complied application


programs or we can say it describes the low-level interface between an application
and the operating system.

8.19. What is the Zero sprint in Agile?

It can be defined as a pre-preparation step to the first sprint. Activities like setting
development environment, preparing backlog, etc need to be done before starting
the first sprint and can be treated as Sprint zero.

8.20. What is Spike?

There may be some technical issues or design problem in the project which needs to
be resolved first. To provide the solution to this problem “Spikes” are created.
Spikes are of two types- Functional and Technical.

8.21. Name some Agile quality strategies.

Some Agile quality strategies are-


1. Re-factoring
2. Small feedback cycles
3. Dynamic code analysis
4. Iteration

8.22. What is the importance of daily stand-up meetings?

Daily stand-up meeting is essential for any team in which team discuss,
1. How much work has been completed?
2. What are the plans to resolve technical issues?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


41
3. What steps need to done to complete the projects etc.?

8.23. What is a tracer bullet?

It can be defined as a spike with the current architecture or the current set of best
practices. The purpose of a tracer bullet is to examine how an end-to-end process
will work and examine feasibility.

8.24. How the velocity of the sprint is measured?

If capacity is measured as a percentage of a 40 hours’ weeks, then, completed story


points * team capacity
If capacity is measured in man-hours, then Completed story points/team capacity.

8.25. How many types of SCRUM Meeting?

There are 5 types of Scrum meetings which occur at a particular time during a Sprint
cycle and each particular type serves a distinct purpose.

1. Sprint Planning Meeting


2. Daily Scrum Meeting
3. Sprint Review Meeting
4. Sprint Retrospective Meeting
5. Backlog Refinement Meeting

Sprint Planning Meeting


At the beginning of every Sprint, Sprint planning meeting is held. Usually, the entire
team is expected to be present during this meeting, including the product owner and
the Scrum master. The goal of this meeting is to develop realistic Sprint backlog and
define the highest priority tasks which need to be done during the length of each
Sprint.

Daily Scrum Meeting


Daily Scrum meeting, or daily standups – as many people call them, are short 15
minutes’ meetings which occur on daily basis. They are typically held at the same time
and same place every day and are strictly time boxed to no longer than 15 minutes.
This ensures the discussion to stay light, relevant, and quick.

• What did you accomplish yesterday?


• What are you working on today?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


42
• Are there any impediments in your way?

Sprint Review Meeting


At the end of each Sprint, a Sprint Review meeting is held. The core objective of this
meeting is to demonstrate the functionality of the product and what has been achieved
during a particular Sprint. Generally, product owner, Scrum Master, and other
stakeholders are present to review the product.

Sprint Retrospective Meeting


A retrospective is a meeting held after a product ships to discuss what happened
during the product development and release process, with the goal of improving
things in the future based on those learnings and conversations.

I Hope, these questions will help you in preparing for the Agile testing and
methodology interview.

Thanks!

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


43
Chapter 9 Database & SQL Concepts

9.1. What is Database

Database is a collection of related data and data is a collection of facts and figures
that can be processed to produce information.

Database management system stores data in such a way that it becomes easier to
retrieve, manipulate, and produce information.

9.2. What is SQL?

Structured Query Language SQL is a database tool that is used to create and
access the database to support software applications.

9.3. What are tables in SQL?

The table is a collection of record and its information at a single view.

9.4. What are the different types of statements supported by SQL?

There are 3 types of SQL statements:

a. DDL (Data Definition Language):

It is used to define the database structure such as tables. It includes three


statements such as CREATE, ALTER, DROP and TRUNCATE.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


44
Some of the DDL Commands are listed below:

CREATE: It is used for creating the table.


CREATE TABLE table_name

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size),

ALTER: The ALTER table is used for modifying the existing table object in the
database.
ALTER TABLE table_name

ADD column_name datatype

OR

ALTER TABLE table_name

DROP COLUMN column_name

b. DML (Data Manipulation Language):

These statements are used to manipulate the data in records. Commonly used DML
statements are INSERT, UPDATE, and DELETE.
The SELECT statement is used as a partial DML statement, used to select all or
relevant records in the table.

c. DCL (Data Control Language):

These statements are used to set privileges such as GRANT and REVOKE
database access permission to the specific user.

9.5. How do we use the DISTINCT statement? What is its use?

The DISTINCT statement is used with the SELECT statement. If the record contains
duplicate values, then the DISTINCT statement is used to select different values
among duplicate records.

Syntax:
SELECT DISTINCT column_name(s)

FROM table_name;

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


45
9.6. What are the different Clauses used in SQL?

Answer:

WHERE Clause: This clause is used to define the condition, extract and display only those
records which fulfill the given condition.
Syntax:
SELECT column_name(s)

FROM table_name

WHERE condition;

GROUP BY Clause: It is used with SELECT statement to group the result of the executed
query using the value specified in it. It matches the value with the column name in tables
and groups the end result accordingly.

Syntax:
SELECT column_name(s)

FROM table_name

GROUP BY column_name;

HAVING clause: This clause is used in association with the GROUP BY clause. It is
applied to each group of results or the entire result as a single group. It is much similar as
WHERE clause but the only difference is you cannot use it without GROUP BY clause
Syntax:
SELECT column_name(s)

FROM table_name

GROUP BY column_name

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


46
HAVING condition;

ORDER BY clause: This clause is used to define the order of the query output either in
ascending (ASC) or in descending (DESC). Ascending (ASC) is set as the default one but
descending (DESC) is set explicitly.
Syntax:
SELECT column_name(s)

FROM table_name

WHERE condition

ORDER BY column_name ASC|DESC;

USING clause: USING clause comes in use while working with SQL JOIN. It is used to
check equality based on columns when tables are joined. It can be used instead of the ON
clause in JOIN.
Syntax:
SELECT column_name(s)

FROM table_name

JOIN table_name

USING (column_name);

9.7. Why do we use SQL constraints? Which constraints we can use


while creating a database in SQL?

Constraints are used to set the rules for all records in the table. If any constraints get
violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.

There are 5 major constraints are used in SQL, such as


• NOT NULL: That indicates that the column must have some value and
cannot be left NULL.
• UNIQUE: This constraint is used to ensure that each row and column has a
unique value and no value is being repeated in any other row or column.
• PRIMARY KEY: This constraint is used in association with NOT NULL and
UNIQUE constraints such as on one or the combination of more than one
column to identify the particular record with a unique identity.
• FOREIGN KEY: It is used to ensure the referential integrity of data in the
table. It matches the value in one table with another using the PRIMARY
KEY.
• CHECK: It ensures whether the value in columns fulfills the specified
condition.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


47
9.8. What is the difference between Null and Empty?

The main difference between null and empty is that the null is used to refer to
nothing while empty is used to refer to a unique string with zero length.

9.9. What are different JOINS used in SQL?

4 major types of Joins are used while working on multiple tables in SQL databases:

INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one matching column.
Syntax:
SELECT column_name(s)

FROM table_name1&nbsp;

INNER JOIN table_name2

ON column_name1=column_name2;

For Example,
In this example, we have a table Employee with the following data:

The second table’s name is Joining.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


48
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

INNER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 4 records selected. Results are:

Employee and Orders tables have a matching customer_id value.

LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its
matched rows from a RIGHT table.
Syntax:
SELECT column_name(s)

FROM table_name1

LEFT JOIN table_name2

ON column_name1=column_name2;

For Example,
In this example, we have a table Employee with the following data:

The second table’s name is Joining.


Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
49
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 4 records selected. You will see the following results:

RIGHT JOIN (RIGHT OUTER JOIN): This join returns all rows from the RIGHT table and its
matched rows from the LEFT table.
Syntax:
SELECT column_name(s)

FROM table_name1

RIGHT JOIN table_name2

ON column_name1=column_name2;

For Example,
In this example, we have a table Employee with the following data:

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


50
The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee

RIGHT JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

Output:
Emp_id Joining_Date

E0012 2016/04/18

E0013 2016/04/19

E0014 2016/05/01

FULL JOIN (FULL OUTER JOIN): This join returns all results when there is a match either
in the RIGHT table or in the LEFT table.
Syntax:
SELECT column_name(s)

FROM table_name1

FULL OUTER JOIN table_name2

ON column_name1=column_name2;

For Example,
In this example, we have a table Employee with the following data:
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
51
The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

FULL OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 8 records selected. These are the results that you should see.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


52
9.10. What are transactions and their controls?

A transaction can be defined as the sequence task that is performed on databases in


a logical manner to gain certain results. Operations like Creating, updating, deleting
records performed in the database come from transactions.
In simple words, we can say that a transaction means a group of SQL queries
executed on database records.

There are 4 transaction controls such as


• COMMIT: It is used to save all changes made through the transaction.
• ROLLBACK: It is used to roll back the transaction. All changes made by the
transaction are reverted back and the database remains as before.
• SET TRANSACTION: Set the name of the transaction.
• SAVEPOINT: It is used to set the point where the transaction is to be rolled back.

9.11. What are the properties of the transaction?

Properties of the transaction are known as ACID properties. These are:


• Atomicity: Ensures the completeness of all transactions performed. Checks whether
every transaction is completed successfully or not. If not, then the transaction is
aborted at the failure point and the previous transaction is rolled back to its initial
state as changes are undone.
• Consistency: Ensures that all changes made through successful transactions are
reflected properly on the database.
• Isolation: Ensures that all transactions are performed independently and changes
made by one transaction are not reflected on others.
• Durability: Ensures that the changes made in the database with committed
transactions persist as it is even after a system failure.

9.12. How many Aggregate functions are available in SQL?

SQL Aggregate functions determine and calculate values from multiple columns in a
table and return a single value.
There are 7 aggregate functions in SQL:
• AVG(): Returns the average value from specified columns.
• COUNT(): Returns number of table rows.
• MAX(): Returns the largest value among the records.
• MIN(): Returns smallest value among the records.
• SUM(): Returns the sum of specified column values.
• FIRST(): Returns the first value.
• LAST(): Returns last value.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


53
9.13. What are Scalar functions in SQL?
Scalar functions are used to return a single value based on the input values.
Scalar Functions are as follows:
• UCASE(): Converts the specified field in the upper case.
• LCASE(): Converts the specified field in lower case.
• MID(): Extracts and returns character from the text field.
• FORMAT(): Specifies the display format.
• LEN(): Specifies the length of the text field.
• ROUND(): Rounds up the decimal field value to a number.

9.14. What are triggers?


Triggers in SQL is kind of stored procedures used to create a response to a specific
action performed on the table such as INSERT, UPDATE or DELETE. You can
invoke triggers explicitly on the table in the database.
Action and Event are two main components of SQL triggers. When certain actions
are performed, the event occurs in response to that action.

Syntax:
CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}

ON table_name [FOR [EACH] {ROW|STATEMENT}]

EXECUTE PROCEDURE functionname {arguments}

9.15. What is View in SQL?


A View can be defined as a virtual table that contains rows and columns with fields
from one or more tables.
Syntax:
CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

9.16. How we can update the view?


SQL CREATE and REPLACE can be used for updating the view.
Execute the below query to update the created view.

Syntax:
CREATE OR REPLACE VIEW view_name AS

SELECT column_name(s)

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


54
FROM table_name

WHERE condition

9.17. Explain the working of SQL Privileges?


SQL GRANT and REVOKE commands are used to implement privileges in SQL
multiple user environments. The administrator of the database can grant or revoke
privileges to or from users of database objects by using commands like SELECT,
INSERT, UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to users
other than the administrator.
Syntax:
GRANT privilege_name

ON object_name

TO {user_name|PUBLIC|role_name}

[WITH GRANT OPTION];

In the above syntax, the GRANT option indicates that the user can grant access to
another user too.

REVOKE command: This command is used to provide database deny or remove


access to database objects.
Syntax:
REVOKE privilege_name

ON object_name

FROM {user_name|PUBLIC|role_name};

9.18. How many types of Privileges are available in SQL?


There are two types of privileges used in SQL, such as
• System privilege: System privilege deals with the object of a particular type and
provides users the right to perform one or more actions on it. These actions
include performing administrative tasks, ALTER ANY INDEX, ALTER ANY
CACHE GROUP CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE
VIEW etc.
• Object privilege: This allows to perform actions on an object or object of another
user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE,
INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES
etc.
9.19. What is SQL Injection?
SQL Injection is a type of database attack technique where malicious SQL
statements are inserted into an entry field of database in a way that once it is
executed, the database is exposed to an attacker for the attack. This technique is

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


55
usually used for attacking data-driven applications to have access to sensitive data
and perform administrative tasks on databases.
For Example,

SELECT column_name(s) FROM table_name WHERE condition;

9.20. What is SQL Sandbox in SQL Server?


SQL Sandbox is a safe place in the SQL server environment where untrusted scripts
are executed. There are 3 types of SQL sandbox:
• Safe Access Sandbox: Here a user can perform SQL operations such as
creating stored procedures, triggers etc. but cannot have access to the
memory as well as cannot create files.
• External Access Sandbox: Users can access files without having the right
to manipulate the memory allocation.
• Unsafe Access Sandbox: This contains untrusted codes where a user can
have access to memory.

9.21. What is the difference between SQL and PL/SQL?


SQL is a Structured Query Language to create and access databases whereas
PL/SQL comes with procedural concepts of programming languages.

9.22. What is the difference between SQL and MySQL?


SQL is a Structured Query Language that is used for manipulating and accessing
the relational database. On the other hand, MySQL itself is a relational database that
uses SQL as the standard database language.

9.23. What is the use of the NVL function?


NVL function is used to convert the null value to its actual value.

9.24. What do you mean by Subquery?


Query within another query is called as Subquery. A subquery is called inner query
which returns output that is to be used by another query.

9.25. How many row comparison operators are used while working
with a subquery?

There are 3-row comparison operators that are used in subqueries such as IN, ANY
and ALL.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


56
9.26. What is the difference between clustered and non-clustered
indexes?
The differences between the two are as follows:
• One table can have only one clustered index but multiple non-clustered indexes.
• Clustered indexes can be read rapidly rather than non-clustered indexes.
• Clustered indexes store data physically in the table or view whereas, non-
clustered indexes do not store data in the table as it has separate structure from
the data row.

9.27. What is the difference between DELETE and TRUNCATE?


The differences are:
• The basic difference in both is DELETE command is DML command and the
TRUNCATE command is DDL.
• DELETE command is used to delete a specific row from the table whereas the
TRUNCATE command is used to remove all rows from the table.
• We can use the DELETE command with WHERE clause but cannot use the
TRUNCATE command with it.

9.28. What is the difference between DROP and TRUNCATE?


TRUNCATE removes all rows from the table which cannot be retrieved back, DROP
removes the entire table from the database and it also cannot be retrieved back.

9.29. What is the difference between Nested Subquery and Correlated


Subquery?
Subquery within another subquery is called Nested Subquery. If the output of a
subquery depends on column values of the parent query table then the query is
called Correlated Subquery.
SELECT adminid(SELEC Firstname+' '+Lastname&nbsp;&nbsp;FROM Employee WHERE

empid=emp. adminid)AS EmpAdminId FROM Employee;

The result of the query is the details of an employee from the Employee table.

9.30. What is Normalization? How many Normalization forms are


there?
Normalization is used to organize the data in such a manner that data redundancy
will never occur in the database and avoid insert, update and delete anomalies.
There are 5 forms of Normalization:
• First Normal Form (1NF): It removes all duplicate columns from the table. It
creates a table for related data and identifies unique column values.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


57
• Second Normal Form (2NF): Follows 1NF and creates and places data
subsets in an individual table and defines the relationship between tables
using the primary key.
• Third Normal Form (3NF): Follows 2NF and removes those columns which
are not related through the primary key.
• Fourth Normal Form (4NF): Follows 3NF and does not define multi-valued
dependencies. 4NF is also known as BCNF.

9.31. What is a Relationship? How many types of Relationships are


there?
The relationship can be defined as the connection between more than one table in
the database.
There are 4 types of relationships:
• One to One Relationship
• Many to One Relationship
• Many to Many Relationship
• One to Many Relationship

9.32. What is Collation?


Collation is a set of rules that check how the data is sorted by comparing it. Such as
character data is stored using correct character sequence along with case
sensitivity, type, and accent.

9.33. What do we need to check in Database Testing?


In Database testing, the following thing is required to be tested:
• Database connectivity
• Constraint check
• Required application field and its size
• Data Retrieval and processing with DML operations
• Stored Procedures
• Functional flow

9.34. What is Database White Box Testing?


Database White Box testing involves:
• Database Consistency and ACID properties
• Database triggers and logical views
• Decision Coverage, Condition Coverage, and Statement Coverage
• Database Tables, Data Model, and Database Schema
• Referential integrity rules

9.35. What is Database Black Box Testing?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


58
Database Black Box testing involves:
• Data Mapping
• Data stored and retrieved
• Use of Black Box testing techniques such as Equivalence Partitioning and
Boundary Value Analysis (BVA)

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


59
Chapter 10 Common SQL Queries

10.1. How to write query for find the highest salary from employees
table.

SELECT name, MAX(salary) as salary FROM employee

10.2. How to write query for find the second highest salary from
employees table.

1st Method
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);

2nd Method
For Second max salary
Select name, salary From Employee ORDER BY Salary DESC LIMIT
1,1;
For third max salary
Select salary From Employee ORDER BY Salary DESC LIMIT 2,1;

10.3. How to write a query to show the details of a student from


Students table whose name start with K?
SELECT * FROM Student WHERE Student_Name like ‘K%’;
Here ‘like’ operator is used to perform pattern matching.

10.4. How to write the query to find the total no of columns in Table?

SELECT TABLE_NAME , count(COLUMN_NAME)


FROM information_schema.columns

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


60
Chapter 11 Application Program Interface (API)

Many of the new modern web applications are built using web-services, micro-services,
and APIs. As testers, we should be knowledgeable and experienced in testing APIs and
Web Services.

Here are some fundamental API Testing Interview Questions mainly aimed at software
testers.

11.1. What is API Testing?

API is a collection of routines, tools, protocols that together are required for building
the software application. Any system software or application software which consists
of multiple APIs can perform Application Programming Interface (API) testing.
This form of testing includes interaction between various or says multiple APIs as
well as the interaction between API and application program. The procedure mainly
includes making API calls using software and observing system response after
receiving the output.

11.2. Enlist some common tests that are performed on APIs.

There can be multiple reasons for performing API testing.


Let us see some common test examples, where this form of testing is used to
verify:
• Any data structure updated by API which requires proper validation.
• Input condition-based return values.
• Call to another API or if any other event is triggered or some interruption is
raised.
• The return values can also be null or wrong results.
• Modification of some resources like an update of the database, process
killing, etc.

11.3. What is the API test environment?

Setting up a test environment of API is a complex method where the configuration of


the server and database is done as per the requirement of the software application.
Graphical User Interface (GUI) is not available in this form of testing.
After installation, API is verified for its proper functioning. In this process initial
environment that invokes API is being set up with a defined set of parameters so that
test results can be examined.

11.4. Explain the API testing approach.

Mentioned below are the factors which determine the approach:

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


61
• Write appropriate test cases for the APIs and use testing techniques like
boundary value analysis, equivalence class, etc. for verifying the functionality.
• Verify the calls of the combination of two or more value-added parameters.
• Define the scope and basic functionality of the API program.
• Define the accurate input parameters.
• Test case execution and comparison of the results with expected results.
• Determining API behavior under conditions like the connection with files, etc.

11.5. Explain in brief the different types of output observed of an API.

API is considered as the essential connecting part of this digital world. It basically
resides in the business logic layer where it performs functions like processing
commands, application coordination, initiates logical decisions, etc.
The main consideration is returning correct results under any type of conditions.
Mainly, the output or results observed of an API are divided into three sections as
follows:

• Returning the result status values as ‘Pass’ or ‘Fail’.


• Result as data or any specific information.
• An event where the call to any API function will initiate the call to another API
function.

11.6. Difference between SOAP and REST API?

• SOAP stands for Simple Object Access Protocol whereas REST stands for
Representational State Transfer.
• SOAP is state full and REST is state less.
• SOAP is a protocol whereas REST is an architectural pattern.
• SOAP uses service interfaces to expose its functionality to client applications
while REST uses Uniform Service locators to access to the components on
the hardware device.
• SOAP needs more bandwidth for its usage whereas REST doesn’t need
much bandwidth.
• Comparing SOAP vs REST API, SOAP only works with XML formats
whereas REST work with plain text, XML, HTML and JSON.
• SOAP cannot make use of REST whereas REST can make use of SOAP.

11.7. Enlist some best practices that are followed to make API testing successful.

Performing tests repeatedly define some best practices for making testing
successful.
Enlisted below are some best practices for API testing:
• Test cases should be grouped under category with expected results that
happen consistently and other typical results.
• Test cases should include selected parameters as well as API call
declarations.
• API load tests are performed to determine system application stress.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
62
• Maintain the limits of the variables used in the tests as well as avoid ‘Test
Chaining’.
• To make ease for the testers, API call is being prioritized and call sequencing
is planned.
• Every input combination and dependencies are considered for complete test
coverage.
• Automation of the test cases, documentation is done as and when required.

11.8. What are the tools used for API testing?

Best API Testing tools:


• SOAPUI
• Runscope
• LOADUI
• Automated API testing
• Curl
• Postman
There are a few more others than the above-listed tools that are used for API testing.

11.9. What are the tools used for API test automation?

Automation testing is a must when we talk about agile development in API testing.
However, the language in which the code is written is also an important factor as it
decides the tool language.
Some important API test automation tools are:
• SOAPUI: It is an open-source API testing tool which is considered as the best
testing tool because of its feature like creating complex validation scripts and
test cases, efficient test coverage, etc.
• HP QTP/UFT: This is now known as HP UFT i.e., Unified Functional Testing.
This tool is basically used for systems without user interface like web
services, etc.
• PARASOFT: This testing tool runs on various platforms and is used to test
API which does not have a Graphical User interface (GUI).
• HTTP master
• NUnit and JUnit testing tools are used where the code is written in .Net and
Java respectively.

11.10. What is the API framework?

API framework is described by the config file which consists of the list of all APIs that
are required to be activated and are activated for any particular program run. This is
essential as every test run does not require all APIs.
The purpose of the ‘Config’ file is to describe and enlist every configurable
component within a test run.

11.11. Explain API documentation.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


63
As it is a well aware fact that, for any foundation, there has to be good
documentation. API documentation likewise, serves as a quick reference for
accessing the library or working within a program.
When we go through any such documents, it must consist of a proper plan, content
source, proper layout or sketch for delivery, information related to each function, etc.

API documentation tools are:


• JavaDoc
• Doxygen
Enlisted below are the categories in which every function is being documented
which mainly revolve around the parameters:
• Function description
• Sequence, syntax, and elements required for each parameter.
• Syntax and type of error message that can occur.
• Links related to functions.

11.12. Name some most used templates for API documentation.

Some free templates which make API documentation much easier and simple
are:
• Slate
• FlatDoc
• Swagger
• API blueprint
• RestDoc
• Miredot
• Web service API Specification.

11.13. Enlist some of the API examples which are very well known and popular.

There are several such examples. Enlisted below are some most popular ones:
• Google Maps API: These are designed mainly for mobile and desktop use with
the help of a flash interface and JavaScript.
• Amazon Advertising API: Amazon is known for their products and thus their
advertising API accesses their product to discover their functionality and thus
advertise accordingly.
• Twitter: The API for twitter is usually in two categories, one for accessing data
and the other for interacting with the twitter search.
• YouTube: This API used for YouTube includes various functionalities including
videos, live streaming, player, etc.

11.14. What are the testing methods that come under API testing?

API testing generally involves the following testing methods:


• Unit testing and Functional testing
• Load testing for testing the performance under load.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


64
• Discovery testing for listing, creating and deleting the number of calls that
have been documented in API.
• Usability testing and Reliability testing for obtaining consistent results.
• Security testing and Penetration testing for validating all types of
authentication.
• Automation testing for creating and executing scripts that require API calls
execution regularly.
• End to end Integration testing and Web UI testing.
• API documentation testing for determining its efficiency and effectiveness.

11.15. Differentiate API testing and Unit Testing.

The difference between API testing and Unit testing can be understood from the
below table:
UNIT testing API Testing

Unit testing is usually performed by developers API testing is performed by the testers for end to
where every functionality is tested separately. end testing of the functionality.

As they have the limited scope of testing, thus basic As they have the broader scope of testing, all
functionalities are only considered for testing. issues that are functional are considered for
testing.

It is a form of white box testing. It is a form of black box testing.

Usually, unit testing is done before the code is API testing is performed after the build is ready for
included in the build. testing.

The Source code is involved in this form of testing. Source code is not involved in this form of testing.

11.16. What challenges are included under API testing?

Challenges are the part of every form of testing and the same goes with API testing
too.
Mentioned below are some common challenges that are faced in API testing:
• The first and foremost challenge is selecting an appropriate parameter and
then its combination.
• Parameter categorization
• Proper sequencing of call is required as this may lead to inadequate
coverage in testing.
• Output verification and validation
• Another important challenge is providing input values, which is very difficult
as GUI is not available in this case.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


65
11.17. What are the types of issues observed while performing API testing?

When testing is performed, then there have to be issues associated with them.
Issues observed while performing this form of testing are not new or much different
but they are common in this category.
Find below the list of such issues/defects:
• Inconsistent or absence of error handling mechanism
• Repetition or redundancy of the functionalities
• Missing required functionality in some cases
• Passing incorrect argument to the input values
• Improper messaging
• Stress and performance issues
• Reliability issues with respect to connection with other APIs
• Multithreading and improper handling issues.

11.18. Why API testing is determined as the most suitable form for Automation
testing?

Yes, it’s true that API testing is now preferred over GUI testing and is considered as
most suitable.
Below are the few reasons behind this statement.
• Verify all the functional paths of the system under test very effectively.
• Provides the most stable interface.
• Easier to maintain and provides fast feedback.

11.19. How is UI level testing different from API testing?

The main consideration of the UI (User Interface) level testing is to test the graphical
interface part of the application include features like font, layout, etc.
Whereas, the main consideration of the API testing is establishing communication
between different software systems and it mainly resides in business logic layer. It
never concentrates on the look of the application.

11.20. What is Test API?

Test Api is known as the library of test building blocks which are essential for
developers and testers for creating testing tools as well as automated test suites.

11.21. What do you know about API errors and warnings?

When something goes wrong i.e. the outcome is not as expected then the error
occurs and warnings are described as a message in the proper format. There can be
one or multiple warnings within the same module.
Different types of warnings that can occur are:
• Parameter validation warning
• Missing module warning
Different types of errors that can occur are:
• Documentation errors
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
66
• Missing module errors
• Parameter validation errors
• Some standard error messages.

11.22. What are HTTP Request and HTTP Response?

POST: The POST is most-often utilized to **create** new resources.

GET: The HTTP GET method is used to **read** (or retrieve) a representation of a resource.

PUT: PUT is most-often utilized for **update** capabilities.

PATCH: PATCH is used for **modify** capabilities.

DELETE: DELETE is pretty easy to understand. It is used to **delete** a resource identified by a


URI.

An HTTP request method is made up of four components:

▪ Request Method – Get, Post, Put, Delete (these are the common ones)
▪ Request URI – the URL of the resource

▪ Request Header – Accept-Language, Accept-Encoding, User-Agent, Host


▪ Request Body – this is the data to be sent to the resource

An HTTP response method is made up of three components:

▪ Response Status Code – 200, 301, 404, 500 (these are the most common ones)

▪ Response Header Fields – Date, Server, Last-Modified, Content-Type


▪ Response Body – this is the data that comes back to the client from the server

11.23. What are the different HTTP Status codes?

2x Success
Code Text Purpose

200 OK For successful GET and PUT requests.

201 Created For a successful POST request.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


67
Code Text Purpose

202 Accepted For a request that resulted in a scheduled task being


created to perform the actual request.

204 No For a successful request that produced no response (such


Content as DELETE requests).

3x Redirection

Code Text Purpose

301 Moved When the API routes have changed (unlikely),


Permanently/Redirection or if the incoming request is not secure ( http ),
the request will be redirected to the secure
( https ) version.

304 Not Modified This response will be sent if the request


included an If-Modified-Since header, but
the resource has not been modified since the
specified date.

4xx Client Error

Code Text Purpose

400 Bad Request Issued when a malformed request was sent.

401 Unauthorized This response is sent when your client failed to provide credentials
or its credentials were invalid.

403 Forbidden Returned when permissions do not allow the operation.

404 Not Found When a particular resource doesn’t exist or couldn’t be found.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


68
Code Text Purpose

405 Method Not The resource was found, but doesn’t support the request method.
Allowed

406 Not Acceptable When the client specifies a response content type in
the Accept header that is not supported.

409 Conflict A change requested by the client is being rejected, due to a


condition imposed by the server. The exact reasons for this
response will vary from one resource to the next

413 Request Entity When the client requests too many objects. For example,
Too Large the limit parameter exceeded the maximum.

415 Unsupported Returned due to issues with the Content-Type header.


Media Type

422 Missing or The request cannot be processed either because it omitted required
Invalid Data fields or because it contained invalid data. See the response for
more details.

429 Too Many When an OAuth client exceeds the rate limit for API requests to a
Requests store.

5xx Server Error

Code Text Purpose

500 Internal Server When an error has occurred within the API.
Error

501 Not When a request method is sent that is not supported by the API
Implemented (e.g., TRACE , PATCH ).

503 Service When the store is “Down for Maintenance,” being upgraded to a new
Unavailable version, or is suspended due to administrative action or a billing issue.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


69
Code Text Purpose

507 Insufficient When the store has reached a limitation for the resource.
Storage

Hope this article will be very helpful for your API Testing interview preparation

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


70
Chapter 12 Object Oriented Programming Basics (OOP)

12.1. What is OOP?


The main aim of OOP is to bind together the data and the functions that operate on them so
that no other part of the code can access this data except that function.

12.2. What is the Access Modifier?


Defines the access type of the method i.e. from where it can be accessed in your application.

• Public: accessible in all classes in your application.


• Protected: accessible within the package in which it is defined and in its subclass(es)(including
subclasses declared outside the package)
• Private: accessible only within the class in which it is defined.
• Default (declared/defined without using any modifier): accessible within same class and
package within which its class is defined.
12.3. What is the class?
A class is a user defined blueprint or prototype from which objects are created. It represents
the set of properties/variables or methods that are common to all objects of one type.

12.4. What is Object?


Object is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.

12.5. What is Method?


A method is a collection of statements that perform some specific task and return the result
to the caller. A method can perform some specific task without returning anything. Methods
allow us to reuse the code without retyping the code.

12.6. What is abstraction?


Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or the non-essential units are not displayed to the user.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does
not know about how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes etc
in the car.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


71
12.7. What is Encapsulation?
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Another way to think about encapsulation is, it is
a protective shield that prevents the data from being accessed by the code outside this
shield.

• Technically in encapsulation, the variables or data of a class is hidden from any other class
and can be accessed only through any member function of own class in which they are
declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.

12.8. What is Inheritance?


Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism
in java by which one class is allowed to inherit the features (fields and methods) of another
class.

12.9. What is Polymorphism?


It refers to the ability of OOPs programming languages to differentiate between entities with
the same name efficiently. This is done by Java with the help of the signature and declaration
of these entities.
Polymorphism in Java are mainly of 2 types
• Overloading
• Overriding
Method Overloading is a Compile time polymorphism. In method overloading, more than
one method shares the same method name with a different signature in the class. In
method overloading, the return type can or cannot be the same, but we have to change
the parameter because, in java, we cannot achieve the method overloading by changing
only the return type of the method.

Method Overriding is a Run time polymorphism. In method overriding, the derived class
provides the specific implementation of the method that is already provided by the base
class or parent class. In method overriding, the return type must be the same or co-variant
(return type may vary in the same direction as the derived class).

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


72
Chapter 13 Selenium WebDriver (Automation)
13.1. What is Automation Testing?

Automation testing or Test Automation is a process of automating the manual


process to test the application/system under test. Automation testing involves the
use of a separate testing tool which lets you create test scripts which can be
executed repeatedly and doesn’t require any manual intervention.

13.2. What are the benefits of Automation Testing?

Benefits of Automation testing are:


1. Supports execution of repeated test cases
2. Aids in testing a large test matrix
3. Enables parallel execution
4. Encourages unattended execution
5. Improves accuracy thereby reducing human-generated errors
6. Saves time and money

13.3. Why should Selenium be selected as a test tool?

Selenium
1. is a free and open source
2. have a large user base and helping communities
3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
4. have great platform compatibility (Windows, Mac OS, Linux etc.)
5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
6. has fresh and regular repository developments
7. supports distributed testing

13.4. What is Selenium? What are the different Selenium components?

Selenium is one of the most popular automated testing suites. Selenium is designed
in a way to support and encourage automation testing of functional aspects of web-
based applications and a wide range of browsers and platforms. Due to its existence
in the open-source community, it has become one of the most accepted tools
amongst the testing professionals.
Selenium is not just a single tool or a utility, rather a package of several testing tools
and for the same reason, it is referred to as a Suite. Each of these tools is designed
to cater different testing and test environment requirements.

The suite package constitutes the following sets of tools:

• Selenium Integrated Development Environment (IDE) – Selenium IDE is a record


and playback tool. It is distributed as a Firefox Plugin.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


73
• Selenium Remote Control (RC) – Selenium RC is a server that allows a user to
create test scripts in the desired programming language. It also allows executing test
scripts within the large spectrum of browsers.
• Selenium WebDriver – WebDriver is a different tool altogether that has various
advantages over Selenium RC. WebDriver directly communicates with the web
browser and uses its native compatibility to automate.
• Selenium Grid – Selenium Grid is used to distribute your test execution on multiple
platforms and environments concurrently.

13.5. What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:


1. Functional Testing
2. Regression Testing

13.6. What are the limitations of Selenium?

Following are the limitations of Selenium:


• Selenium supports testing of only web-based applications
• Mobile applications cannot be tested using Selenium
• Captcha and Barcode readers cannot be tested using Selenium
• Reports can only be generated using third-party tools like TestNG or JUnit.
• As Selenium is a free tool, thus there is no ready vendor support through the
user can find numerous helping communities.
• The user is expected to possess prior programming language knowledge.

13.7. When should I use Selenium IDE?

Selenium IDE is the simplest and easiest of all the tools within the Selenium
Package. Its record and playback feature makes it exceptionally easy to learn with
minimal acquaintances to any programming language. Selenium IDE is an ideal tool
for a naïve user.

13.8. What is Selenese?

Selenese is the language which is used to write test scripts in Selenium IDE.

13.9. What are the different types of locators in Selenium?

The locator can be termed as an address that identifies a web element uniquely
within the webpage. Thus, to identify web elements accurately and precisely we
have different types of locators in Selenium:
• ID
• ClassName
• Name
• TagName
• LinkText
• PartialLinkText
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
74
• Xpath
• CSS Selector
• DOM

13.10. What is the difference between assert and verify commands?

Assert: Assert command checks whether the given condition is true or false. Let’s
say we assert whether the given element is present on the web page or not. If the
condition is true then the program control will execute the next test step but if the
condition is false, the execution would stop and no further test would be executed.
Verify: Verify command also checks whether the given condition is true or false.
Irrespective of the condition being true or false, the program execution doesn’t halt
i.e. any failure during verification would not stop the execution and all the test steps
would be executed.

13.11. What is an XPath?

XPath is used to locate a web element based on its XML path. XML stands for
Extensible Markup Language and is used to store, organize and transport arbitrary
data. It stores data in a key-value pair which is very much similar to HTML tags. Both
being markup languages and since they fall under the same umbrella, XPath can be
used to locate HTML elements.
The fundamental behind locating elements using XPath is the traversing between
various elements across the entire page and thus enabling a user to find an element
with the reference of another element.

13.12. What is the difference between Static Xpath and Dynamic Xpath?

An absolute xpath in HTML Document Object Modal (DOM) starts with html e.g.

1. html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the DOM element and generates xpath
starting from that element e.g.

1. //*[@id='answers']/h2[1]/a[1]

Single Slash “/” – Single slash is used to create Xpath with absolute path.
Double Slash “//” – Double slash is used to create Xpath with relative path.

13.13. When should I use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple
platforms and browsers concurrently so as to achieve distributed test execution,
testing under different environments and saving execution time remarkably.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
75
13.14. How do I launch the browser using WebDriver?

The following syntax can be used to launch Browser:


WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();

13.15. What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are:


• FirefoxDriver
• InternetExplorerDriver
• ChromeDriver
• SafariDriver
• OperaDriver
• AndroidDriver
• IPhoneDriver
• HtmlUnitDriver

13.16. What are the different types of waits available in WebDriver?

There are two types of waits available in WebDriver:


1. Implicit Wait
2. Explicit Wait

Implicit Wait: Implicit waits are used to provide a default waiting time (say 30
seconds) between each consecutive test step/command across the entire test script.
Thus, the subsequent test step would only execute when the 30 seconds have
elapsed after executing the previous test step/command.

Explicit Wait: Explicit waits are used to halt the execution till the time a particular
condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit
waits are applied for a particular instance only.

There are some common conditions that are frequently of use when automating web
browsers.

• title_is
• title_contains
• presence_of_element_located
• visibility_of_element_located
• visibility_of
• presence_of_all_elements_located
• text_to_be_present_in_element
• text_to_be_present_in_element_value
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
76
• frame_to_be_available_and_switch_to_it
• invisibility_of_element_located
• element_to_be_clickable
• staleness_of
• element_to_be_selected
• element_located_to_be_selected
• element_selection_state_to_be
• element_located_selection_state_to_be
• alert_is_present

13.17. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);

13.18. How can you find if an element in displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the
web elements. These web elements can be buttons, drop boxes, checkboxes, radio
buttons, labels etc.
1. isDisplayed()
2. isSelected()
3. isEnabled()

Syntax:
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

13.19. How can we get a text of a web element?

Get command is used to retrieve the inner text of the specified web element. The
command doesn’t require any parameter but returns a string value. It is also one of
the extensively used commands for verification of messages, labels, errors etc
displayed on the web pages.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


77
Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();
13.20. How to select value in a dropdown?

The value in the dropdown can be selected using WebDriver’s Select class.
Syntax:
selectByValue:
Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select
(driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);

13.21. What are the different types of navigation commands?

Following are the navigation commands:


navigate().back() – The above command requires no parameters and takes back
the user to the previous webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page
with reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page
there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window
and navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);

13.22. How to click on a hyper link using linkText?

driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and
thus the user would be re-directed to the corresponding page.

The above-mentioned link can also be accessed by using the following command.

driver.findElement(By.partialLinkText(“Goo”)).click();

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


78
The above command finds the element based on the substring of the link provided in
the parenthesis and thus partialLinkText() finds the web element with the specified
substring and then clicks on it.

13.23. How to handle frame in WebDriver?

An inline frame acronym as iframe is used to insert another document within the
current HTML document or simply a web page into a web page by enabling nesting.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();

13.24. When do we use findElement() and findElements()?

findElement(): findElement() is used to find the first element in the current web page
matching to the specified locator value. Take a note that only first matching element
would be fetched.
Syntax:
WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web
page matching to the specified locator value. Take a note that all the matching
elements would be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList
= driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));

13.25. What is the difference between driver.close() and driver.quit command?

They do a similar thing but not exactly the same.


close(): WebDriver’s close() method closes the web browser window that the user is
currently working on or we can also say the window that is being currently accessed
by the WebDriver.
quit(): driver.quit() is used to exit the browser, end the session, tabs, pop-ups etc.

13.26. Can Selenium handle windows-based pop up?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


79
Selenium is an automation testing tool which supports only web application testing.
Therefore, windows pop up cannot be handled using Selenium.

13.27. How can we handle web-based pop-up?

WebDriver offers the users a very efficient way to handle these pop-ups using Alert
interface. There are the four methods that we would be using along with the Alert
interface.
• void dismiss() – The dismiss() method clicks on the “Cancel” button as soon
as the pop-up window appears.
• void accept() – The accept() method clicks on the “Ok” button as soon as the
pop-up window appears.
• String getText() – The getText() method returns the text displayed on the alert
box.
• void sendKeys(String stringToSend) – The sendKeys() method enters the
specified string pattern into the alert box.
Syntax:
// accepting javascript alert
Alert alert = driver.switchTo().alert();
alert.accept();

13.28. How to assert the title of the web page?

//verify the title of the web page


assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the
page”));

13.29. How to mouse hover on a web element using WebDriver?

WebDriver offers a wide range of interaction utilities that the user can exploit to
automate mouse and keyboard events. Action Interface is one such utility which
simulates the single user interactions.
Thus, In the following scenario, we have used Action Interface to mouse hover on a
drop down which then opens a list of options.

Sample Code:
// Instantiating Action Interface

Actions actions=new Actions(driver);

// howering on the dropdown

actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();

// Clicking on one of the items in the list options

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


80
WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));

subLinkOption.click();

13.30. How to retrieve CSS properties of an element?

The values of the css properties can be retrieved using a get() method:
Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);

13.31. What is Junit?

Junit is a unit testing framework introduced by Apache. Junit is based on Java.

13.32. What are Junit annotations?

Following are the JUnit Annotations:


• @Test: Annotation lets the system know that the method annotated as @Test is a
test method. There can be multiple test methods in a single test script.
• @Before: Method annotated as @Before lets the system know that this method
shall be executed every time before each of the test methods.
• @After: Method annotated as @After lets the system know that this method shall be
executed every time after each of the test method.
• @BeforeClass: Method annotated as @BeforeClass lets the system know that this
method shall be executed once before any of the test methods.
• @AfterClass: Method annotated as @AfterClass lets the system know that this
method shall be executed once after any of the test methods.
• @Ignore: Method annotated as @Ignore lets the system know that this method shall
not be executed.

13.33. What is TestNG and how is it better than Junit?

TestNG is an advanced framework designed in a way to leverage the benefits by


both the developers and testers. With the commencement of the frameworks, JUnit
gained enormous popularity across the Java applications, Java developers and Java
testers with remarkably increasing the code quality. Despite being easy to use and
straightforward, JUnit has its own limitations which give rise to the need of bringing
TestNG into the picture. TestNG is an open source framework which is distributed
under the Apache Software License and is readily available for download.
TestNG with WebDriver provides an efficient and effective test result format that can,
in turn, be shared with the stakeholders to have a glimpse on the
product’s/application’s health thereby eliminating the drawback of WebDriver’s
incapability to generate test reports. TestNG has an inbuilt exception handling
mechanism which lets the program to run without terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them
are:
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
81
• Added advance and easy annotations
• Execution patterns can set
• Concurrent execution of test scripts
• Test case dependencies can be set
13.34. What is a framework?

The framework is a constructive blend of various guidelines, coding standards,


concepts, processes, practices, project hierarchies, modularity, reporting
mechanism, test data injections etc. to pillar automation testing.

13.35. What are the advantages of the Automation framework?

The advantage of Test Automation framework


• Reusability of code
• Maximum coverage
• Recovery scenario
• Low-cost maintenance
• Minimal manual intervention
• Easy Reporting

13.36. What are the different types of frameworks?

Below are the different types of frameworks:

1. Module Based Testing Framework:


The framework divides the entire “Application Under Test” into the number of logical
and isolated modules. For each module, we create a separate and independent test
script. Thus, when these test scripts have taken together builds a larger test script
representing more than one module.
2. Library Architecture Testing Framework:
The basic fundamental behind the framework is to determine the common steps and
group them into functions under a library and call those functions in the test scripts
whenever required.
3. Data Driven Testing Framework:
Data Driven Testing Framework helps the user segregate the test script logic and
the test data from each other. It lets the user store the test data into an external
database. The data is conventionally stored in “Key-Value” pairs. Thus, the key can
be used to access and populate the data within the test scripts.
4. Keyword Driven Testing Framework:
The Keyword Driven testing framework is an extension to Data-driven Testing
Framework in a sense that it not only segregates the test data from the scripts, it
also keeps the certain set of code belonging to the test script into an external data
file.
5. Hybrid Testing Framework:
Hybrid Testing Framework is a combination of more than one above mentioned
frameworks. The best thing about such a setup is that it leverages the benefits of all
kinds of associated frameworks.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


82
6. Test Driven Development (TDD) Imp
TDD stands for Test Driven Development. In this software development technique,
we create the test cases first and then write the code underlying those test cases.

7. Behavior Driven Development (BDD) imp


Behavior Driven Development framework allows automation of functional validations
in an easily readable and understandable format to Business Analysts, Developers,
Testers, etc.

Example: Write the behavior of the application for entering the username and
password.
Scenario: Login check
Given I am on the login page
When I enter "username" username
And I enter "Password" password
And I click on the "Login" button
Then I am able to login successfully.

8. Page Object Model (POM) imp

Page Object Model (POM) is a design pattern, popularly used in test automation that
creates Object Repository for web UI elements. The advantage of the model is that it
reduces code duplication and improves test maintenance.

Advantages of POM

1. Page Object Design Pattern says operations and flows in the UI should be
separated from verification. This concept makes our code cleaner and easy to
understand.
2. The Second benefit is the object repository is independent of test cases, so
we can use the same object repository for a different purpose with different
tools.
3. Code becomes less and optimized because of the reusable page methods in
the POM classes.
4. Methods get more realistic names which can be easily mapped with the
operation happening in UI. i.e. if after clicking on the button we land on the
home page, the method name will be like 'gotoHomePage()'.

13.37. How can I read test data from excels?

Test data can efficiently be read from excel using JXL or POI API.

13.38. What is the difference between Selenium and QTP?

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


83
Feature Selenium Quick Test Professional (QTP)

Browser Selenium supports almost all the popular QTP supports Internet Explorer, Firefox and
Compatibility browsers like Firefox, Chrome, Safari, Internet Chrome. QTP only supports Windows
Explorer, Opera etc. Operating System

Distribution Selenium is distributed as an open-source tool QTP is distributed as a licensed tool and is
and is freely available commercialized

Application Selenium supports testing of only web-based QTP supports testing of both the web-based
under Test applications application and windows based application

Object Object Repository needs to be created as a QTP automatically creates and maintains
Repository separate entity Object Repository

Language Selenium supports multiple programming QTP supports only VB Script


Support languages like Java, C#, Ruby, Python, Perl
etc

Vendor Support As Selenium is a free tool, user would not get Users can easily get the vendor’s support in
the vendor’s support in troubleshooting issues case of any issue

13.39. Can WebDriver test Mobile applications?

WebDriver cannot test Mobile applications. WebDriver is a web-based testing tool,


therefore applications on the mobile browsers can be tested.

13.40. Can captcha be automated?

No, captcha and barcode reader cannot be automated.

13.41. What is Object Repository? How can we create an Object Repository in


Selenium?

Object Repository is a term used to refer to the collection of web elements belonging
to Application Under Test (AUT) along with their locator values. Thus, whenever the
element is required within the script, the locator value can be populated from the
Object Repository. Object Repository is used to store locators in a centralized
location instead of hardcoding them within the scripts.
In Selenium, objects can be stored in an excel sheet which can be populated inside
the script whenever required.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


84
13.42. What is an Exception?

Exceptions are events due to which java program ends abruptly without giving
expected output. Java provides a framework where a user can handle exceptions.

13.43. What is exception handling?

When you start working with Selenium webdriver, you will come across different
exceptions based on the code you write. When an exception occurs, the normal flow
of program halts and an exception object is created. Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Though there are many Exception classes under WebDriverException, we


commonly see the below ones.

• NoSuchElementException
• NoSuchWindowException
• NoSuchFrameException
• NoAlertPresentException
• InvalidSelectorException
• ElementNotVisibleException
• ElementNotSelectableException
• TimeoutException
• NoSuchSessionException
• StaleElementReferenceException

13.44. How to Switch Tabs in window using selenium?

p = driver.current_window_handle
parent = driver.window_handles[0]
child = driver.window_handles[1]
driver.switch_to.window(child)

13.45. What is SELF in python?

__init__ method
"__init__" is a reserved method in python classes. It is called as a constructor in
object oriented terminology. This method is called when an object is created from
a class and it allows the class to initialize the attributes of the class.

Hope in this article you will find answers to most frequently asked Selenium and
WebDriver Interview questions.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


85
Chapter 14 JMeter Concepts (Automation)

14.1. Explain the architecture of JMeter.

JMeter is a Java-based open-source application that is basically designed for the


purpose of Load Testing. It supports all major protocols that are supported in Load
Runner. Unlike any browser, JMeter works on levels of protocols and does not
execute JavaScript present in HTML web pages.

14.2. Does JMeter simulate actual browser behavior?

No, JMeter does not support the actual browser behavior. It does not render the
HTML webpages as the normal browser does. The response can be viewed in
HTML format but the actual timings are not present in the generated samples.

14.3. What is Distributed testing?

Distributed Testing means using multiple machines for load testing in which one of
the machines can be made master and others can be kept as a slave. It is very
important to note that all the machines should be on the same network and should
have the same version of Java and JMeter.

14.4. What is the use of Regular Expression in JMeter?

Regular Expression is used for extracting some values dynamically from the
responses. These values can be used in the subsequent request or can be saved for
reporting purposes. Regular Expression is used in both Pre-Processors as well as
Post Processors.

14.5. What are the types of processors in JMeter?

Basically, there are two types of processors in JMeter namely Pre-Processor and
Post Processor.
Pre-Processors execute before the main sampler and can change the scope of the
sampler whereas Post Processors execute after the main sampler and are
applicable to all samplers in the same scope of Test Plan. They can be used to
extract some fields from the server response and store them in variables.

14.6. What are the different ways of Data Parameterization in JMeter?

Data Parametrization makes the scripts reusable where the values is not required to
be hardcoded for the same request with different parameters.
Below is the data parametrization that is supported in JMeter:
• CSV Data Set Config
• User-Defined Variables.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


86
14.7. What are the maximum recommended threads on a single system?

It depends on the hardware configuration of your system which includes a processor,


JVM, allocated memory -Xmx, etc.
Other factors that impact thread count are the number of components in your test
plan i.e., the number of config elements or processors and it also depends on
whether you are using GUI/Non-GUI Mode.

14.8. Explain the difference between Gaussian and Poisson Timers.

Both Gaussian and Poisson Timers work on a mathematical formula with some
constant delay and additional offset. Difference between the two lies in the fact that
how the lambda value is calculated in the case of Poisson timer and how deviation is
calculated in the case of Gaussian Timer.

14.9. What are the major differences between JMeter and Load Runner?

JMeter is considered as the major competitor of Load Runner in the


industry. Enlisted are some of the major differences:

Load Runner JMeter

Licensed Software Open Source tool.

Developed by Mercury Developed by Apache.

UI is very impressive It lacks in UI

It has more technical capabilities. Less technically sound as compared to Load Runner.

Supports SAP, Siebel and Peoplesoft. Doesn’t support SAP and Siebel

14.10. What is the use of co-relation in JMeter?

Co-relation is a process of extracting the values from the server response and
storing it in a variable to be used in any other request which is to follow.
For Example, for testing any login functionality if you have to use the session
ID/cookie ID, you can extract the values from the response of GET Request of the
login page and then dynamically use the same while making POST request for a
login.

14.11. What are the different types of listeners?

Listeners are used for storing the execution results of load testing in different forms
be it in a table, graph, tree or in any other presentable format so that it can be
presented to the client. There are different type of inbuild listeners in JMeter and
many others can be imported into it by using plugins as per the requirement.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
87
Some of the inbuild listeners are:
• View results in Table
• View results in Tree
• Graph results
• Aggregate graph
• Aggregate report
• Assertion results
• Response time graph

14.12. Explain the flow of the Test Script Recorder.

HTTP(s) Test Script Recorder is used to record all the Http(s) requests going to the
server from your application. Some configurations require to be done in JMeter in
order to make it work.
Steps followed to record https traffic are:
• Add HTTP(s) Test script recorder to WorkBench.
• Enter the port number to start your proxy server.
• Choose the target either as “Workbench” or add a Recording Controller in your
test plan and select the same target for storing all the recordings under it.
• Start the proxy server.
• Configure your browser with manual proxy settings pointing to the same port
number used in the test script recorder.

14.13. Can JMeter record actions from mobile? If yes, how?

Yes, JMeter can record HTTP or Https request going to the server from your mobile
application also. It is required that mobile and JMeter are on the same network.
Below is the configuration required:
• Configure your proxy server in JMeter to run at a specified port.
• Set up the proxy on your mobile wifi settings and enter the same port number
that is used in the recorder.
• Install the Root CA certificate on your mobile.
• Hit server requests from your mobile and observe it getting captured by the
specified controller.

14.14. How to do master-slave configuration in JMeter?

Master-slave configuration is a part of distributed testing in which more than one


machine is used to perform load testing of the server under test.
It is very important that all machines are on the same network and all have the same
version of JMeter. In distributed testing, one machine considered as the master and
the others are kept as slaves by doing some configurations.

The process is specified below:


• On the master machine, edit the JMeter. Properties file and add the IP
addresses of slave machines against the remote host field in the file.
• Save the file and open the JMeter again.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


88
• Now, from the RUN menu in JMeter, select Remote Start and choose the IP
of the machine to be invoked.
• Choose RUN menu and select Remote Start all to start all the slave machines
for your testing.

14.15. What are the JMeter supported protocols?

JMeter supports various standard protocols like:


• HTTP/HTTPs
• SOAP
• LDAP
• FTP
• SMTP
• TCP

14.16. Explain the syntax of JMeter variables and functions.

Just as in any other programming language, variables and functions are used in
JMeter also in order to make the scripts reusable.
Syntax of Variable – ${var}
There are many inbuilt functions that are available in JMeter to perform various
actions. Function string can be generated from the Function Dialogue Box itself.

For Example, if you want to get the machine IP stored in a machineIP variable, you
can use the string ${__machineIP(machineIP)}.

14.17. Why is it recommended to run JMeter in GUI mode?

JMeter tests can be run both GUI as well as Non-GUI Mode. It is highly
recommended to run the load test in non-GUI mode because the AWT event thread
can kill the tests in case of high load scenarios.
The various non-GUI mode supported with JMeter are:
• Command-line
• ANT plugin
• MAVEN plugin
• Jenkins

14.18. Is it possible to run selenium scripts in JMeter? If yes, how?

Yes, it is possible to run selenium scripts in JMeter to get some ideas on their
performance.
There are two ways of doing it. Either you can use JUnit libraries to build selenium
scripts and save as Jars and copy the same in the JMeter directory. And then add
JUnit sampler to your test plan and import the Jar file.

Otherwise, the Webdriver sampler plugin can be added in the JMeter ext folder.
Restart the JMeter. Write your selenium code in the Webdriver sampler and then
execute it to see the performance.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
89
14.19. How do you manage sessions and cookies in JMeter?

Sessions and cookies can be managed in JMeter by using config elements such as
HTTP Cache Manager which provides an option to clear the cookies in every
iteration and also allows to add user-defined cookies.
HTTP Cache manager helps you in clearing cache after each iteration as per your
requirement in the load tests and also limits the number of elements that can be
stored in the cache. Both of these config elements can be attached to the HTTP
sampler.

14.20. What are the important steps for testing JDBC request?

JDBC requests are used to establish a connection with the databases and then
measure the response time of the queries.
Important steps for testing JDBC requests are:
• Setting up Config Element, JDBC Connection configuration in which
Database URL and JDBC Driver Class needs to be added as per the
database which is being used. Also, add the variable name for this
connection configuration so as to use it in the sampler.
• Add JDBC Request. Add the same variable name added above and write
your queries to the test.

14.21. What is BeanShell scripting?

BeanShell is a lightweight Java scripting that is used in JMeter to perform some


complex task. BeanShell sampler can perform various functions with the use of
coding. You can print the thread number, get the current sampler executed, fetch the
cookies, etc.

14.22. Can JMeter measure the performance of a complete application? For Example,
you have multiple screens in your mobile app. Can JMeter measure the time
taken to flip the screens?

No, JMeter does not measure the transition time between the screens. It can only
measure the server actions not the UI interactions.

14.23. What is a Root CA certificate?

HTTPS connection requires a certificate to authenticate the connections which get


established when the browser hits the webserver. JMeter generates it temporarily to
intercept the SSL traffic in order to record the actions. For recording actions via
mobile, you need to have this certificate on your mobile to record the actions.

14.24. Which factors decide the maximum threads that one should generate per
system?

It depends on the hardware of the system.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


90
For Example, on a 2-3 GHz CPU, 400-600 threads can be generated. It also
depends on the components in your test plan. More the processors and XML parsing
elements, the more the CPU load and hence fewer threads. For high load, it is
recommended to use multiple machines for load testing.

14.25. What is Tidy Parsing?

Tidy Parsing is a type of parsing that is used in Xpath extractor. If the response is in
pure XML then tidy parsing is not required whereas, in the case of XHTML, it is
mandatory to check the tidy parsing option in order to fetch the correct results.

14.26. What are the important plugins that are supported in JMeter?

JMeter supports different types of plugins which are helpful in generating high-quality
results.
Below are the major plugins that are supported:
• Thread group plugin – Stepping thread group plugin.
• Samplers’ plugins like Webdriver.
• Listener’s plugins.

14.27. What are the types of the controller in JMeter?

Controllers are used in JMeter to control the flow of execution of requests.


Below are the controllers that are used in JMeter:
• Recording controller
• IF controller
• While controller
• Transaction controller
• Loop controller
• Simple controller
• Module controller

14.28. What are the samplers?

How does a Jmeter knows what type of request has been sent to server???
It is through Samplers. Samplers are a must to add to a Test Plan as only it can let
Jmeter know what type of request need to go to which server and with any
predefined parameters or not. Requests could be HTTP, HTTP(s), FTP, TCP,
SMTP, SOAP, JDBC etc.

14.29. What are the Assertions.

Till now, we have covered how JMeter hits the server and how the responses are
displayed via listeners. To ensure that the response received is correct and as per
expectation, we need to add assertions. Assertions are simply validations which we
need to put on responses to compare the results.
Below are the types of assertions commonly used:
• Response Assertion

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


91
• Duration Assertion
• Size Assertion
• XML Assertion
• HTML Assertion

I’m sure that this article on JMeter interview questions would have helped to enrich your
knowledge on JMeter concepts to a great extent.

A thorough understanding of all the questions covered here would help you to crack any
interview confidently.

We wish you all the success!!

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


92
Chapter 15 Aptitude Questions

15.1. If you have a 5-litre jug and a 3-litre jug, how would you measure exactly 4
liters?

Answer
1. Fill the 3L jug fully and empty it in the 5L jug
2. Now again fill 3L fully and pour its water in the 5L jug (remember it already has 3 liters of
water in it) until it full.
3. Now you're left with only 1 liter of water in the 3L jug (*hope you are getting it)
4. Now empty 5L jug and pour that remaining 1-liter water that we got in step 3 into the 5L
jug.
a. Now 5L jug contains 1 liter of water.
5. Now fill the 3L jug fully and empty it into the 5L jug so you will now have 4 liters of water
in 5L jug.
That's how you get 4litres of water.

15.2. I give you 4 tablets which contain 2 for fever and 2 for cold, all the same
size, shape, taste, weight and color, no cover. You have to take 1 cold and 1
fever tablet right now. How will you choose correctly?

Answer

So basically, you have 4 tablets. 2 for cold and other 2 for fever. Now start dividing the
tablets into half. Keep one half in your hand and other half on table. Once you are
done dividing all the tablets into half, take either of them. Problem solved.

15.3. There is a room with a door (closed) and three light bulbs. Outside the
room, there are three switches, connected to the bulbs. You may manipulate
the switches as you wish, but once you open the door you can’t change
them. Identify each switch with its bulb. All bulbs are in working condition.

Answer

Let the bulbs be X, Y, and Z


Turn on switch X for 5 to 10 minutes. Turn it off and turn on switch Y. Open
the door and touch the light bulb.
1. if the light is on, it is Y
2. if the light is off and hot, it is X
3. if the light is off and cold, it is Z

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


93
15.4. A blind man is alone on a deserted island. He has two blue pills and two red
pills. He must take exactly one red pill and one blue pill or he will die.

Answer

Firstly, break each of the pills in half, and as you do this pop one half in your mouth
and lay the other half aside for tomorrow. When he’s done this with all four pills he will
have consumed one red pill and one blue pill. And have the same leftover.

15.5. A newspaper made of 16 large sheets of paper folded in half. The


newspaper has 64 pages altogether. The first sheet contains pages 1, 2, 63,
64.
If we pick up a sheet containing page number 45. What are the other pages
that this sheet contains?

Answer

On the back of 45, it is 46. The pages are such that for each page p, 65-p
will be also on the same page.
Then,
65-45 = 20
65-46 = 19
So, the four pages in this sheet are 19, 20, 45, 46.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


94
15.6. You have a birthday cake and have to cut it into 8 equal pieces by making 3
cuts only. How do you do it?

Answer

Step 1: Cut the cake into quarters (4 pieces) using 2 of the cuts – one
horizontally down the center of the cake and the other vertically down the
center of the cake. This will leave you with 4 pieces (or slices) of cake.

Step 2: Then take all 4 pieces and arrange them in a stack that is 4 pieces
high.
Step 3: Finally, you can just cut that stack of 4 pieces in half – using your third
and final cut – and then you will end up with 8 pieces of cake!

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


95
15.7. Which letter replaces the “?”:
L:O
R:I
E:V
M:?
Solution : N, because if we assign the values as A=1, B=2…..Z=26, then
each pair adds upto 27.
example : L O
12+15 = 27.
And for M:N
13+14=27

15.8. A Lady (L) bought an item of Rs 100 from the Shopkeeper (C). She paid him
through a 500 Rs Note. Realizing that he did not have change, the
shopkeeper C got change for that note from another shopkeeper (S) and
paid Rs 400 to the Lady.

After a few days, S realized that the note is fake, And this railed at C and took
500 Rs back from him.
So in this whole process how much money did C loose in the end?

Answer: 500

15.9. What is half of two plus two?


A) Half of 2+2 = (Half of 2) + 2 = (1) + 2 = 3 .

B) Half of 2+2 = Half of (2+2) = (.5)(4) = 2.

This is based on the user perspective for the perfect solution based on the situation
where in it is used.

But, technically to answer this, the correct answer is 3.

15.10. Hand shake puzzle formula to calculate no of handshakes.


The formula for the number of handshakes possible at a party with n people is

# handshakes = n*(n - 1)/2.

This is because each of the n people can shake hands with n - 1 people (they would
not shake their own hand), and the handshake between two people is not counted
twice.

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


96
This formula can be used for any number of people. For example, with a party of 5
people, find the number of handshakes possible.

# handshakes = 5*(5 - 1)/2.

# handshakes = 5*(4)/2.

# handshakes = 20/2.

# handshakes = 10

So, there are 10 handshakes that can be made between 5 people.

15.11. You have 9 balls, equally big, equally heavy - except for one, which is a little
heavier.

How would you identify the heavier ball if you could use a pair of balance
scales only twice?
ANS:

Divide the 9 balls into 3 groups of 3. Compare the weight of two of those groups.

The heavier group should then be obvious, it will either tip the scales, or, if the scales
stay balanced, then it is the group you didn't include.

Now, choose 2 balls from this group and compare their weights, and using the same
logic as before, the heavier ball will be obvious.

Thanks

Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer


97
Table of Contents

What is API? 4

What is API Testing? 6

What is REST API? 6

Difference between REST API vs SOAP API. 8

What to Test in API Testing? 8

HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10

HTTP Methods explained. 12


HTTP GET Method Explained - 12
HTTP POST Method Explained - 13
HTTP PUT Method Explained - 13
HTTP PATCH Method Explained - 14
HTTP DELETE & OPTIONS Method Explained - 14
HTTP HEAD/TRACE Method Explained - 15

How to Test an API ( API Testing)? 15

API Testing tools 16

How to do API Testing using Postman 16


What is API?

API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.

For example, It like a connector as seen in the picture. All data connects to our organization through API.

In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.

API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API

Type of APIs :-
What is API Testing?

When we talk about API Testing,

API testing is testing that APIs and its integration with the services.

It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..

In this definite guide,


We are basically discussing about the REST API Testing.Where we need to test the REST APIs for the
validation, error codes and load testing.

What is REST API?


As REST is an acronym for REpresentational State Transfer, statelessness is key. An API can be REST if it
follows the below constraints.

The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.

1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand

Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,

First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.

Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..

Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.

Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.

Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.

Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.

If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).

SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.

Enough of background lets come to topic…

What to Test in API Testing?

● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.

Lets understand why API Testing is important…


Why you should perform API Testing?
● Many of the services that we use every day rely on hundreds of different interconnected APIs, if any
one of them fails then the service will not work.

● Right now, Internet uses millions of APIs and they should be tested thoroughly.

● Developers make mistake and they create buggy APIs..

● Validation of APIs is very important which are going live to production.

Above image shows the architecture of an application and notice that API Testing is important part..

Now…

Lets learn one more concept HTTP Methods

HTTP - Fundamentals

HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.

HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.

What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.

GET /spec.html HTTP/1.1


Host: www.example.org
Cookie: theme=light; sessionToken=abc123

Record the user's browsing activity.


Which pages were visited in the past.
Contain the name of the domain & Lifetime.

Tool : EditThisCookie - http://bit.ly/1oe1o08

What is Authentication and its types lets understand it...

What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.

Basic authentication - String is encoded with Base64.


curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com
Digest Authentication - Authentication is performed by transmitting the password in an ENCRYPTED
form.(With Some Salt etc)

OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.

E.g OAuth 1, 2.

More authentication are discussed here -


https://scrolltest.com/2018/11/22/how-to-handle-authentications-with-postman/

In Client as Browser and Server as DB with the service running in PHP.

We can create an HTTP request from browser by typing a URL.

Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL

Lets Understand what all HTTP methods are present


HTTP Methods explained.

HTTP GET Method Explained -

.
HTTP POST Method Explained -

HTTP PUT Method Explained -


HTTP PATCH Method Explained -

HTTP DELETE & OPTIONS Method Explained -


HTTP HEAD/TRACE Method Explained -

Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.

How to Test an API ( API Testing)?

Before that take a look into the example api that can available freely.

https://api.chucknorris.io/jokes/random

Here Keys are


cateroy, icon_url, id, url and value and they have corresponding values as String or number.
API Testing can be done manually or using a Tools. It is always recommend to certain tools.

Lets learn API Testing using our favorite tools..


Below is the list of API testing tools, You can learn or use whichever tool you feel is great for you, I encourage
you to start with Postman it's an awesome API Testing tool which provide lots of feature like command line,
CI/CD and monitoring of APIs with testcase support.

API Testing tools

● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD

API Testing using POSTMAN


What is Postman?

First of all, let’s understand what is Postman.

It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.

You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.

Its available in the MacOS, Windows and Linux as Native app.

Download Postman - https://www.getpostman.com


Major features of postman
Manual testing interview question

1. WHAT IS SOFTWARE TESTING?


→ It is a process of analyzing s/w item to detect the differences between existing and
required conditions and to evaluate the features of the s/w item.
→ It is a verification and validation process.
→Process of demonstrating that errors are not present.

2. DIFFERENCE BETWEEN VERIFICATION AND VALIDATION?


Verification→
o It is a process of confirming whether the s/w meets it’s requirement or not.
o Process of examining/reviewing of work product.
o Are we building the product right?
o It is a QA activity.
o It’s a static process performed at compile time.
o It is performed by a QA team or by developer.
o Cost and time effective.
o Activities involve in this is testing the application.
Validation→
o It is a process of confirming whether the s/w meets user’s requirement or not.
o Process of executing a product & examining how it behaves.
o Are we building the right product?
o It is a QC activity.
o It’s a dynamic process performed at run time.
o It is performed by a QC team or by tester.
o Cost and time taking.
o Activities involve in this are inspections, reviews, walk-through.

3. DIFFERENCE BETWEEN QUALITY CONTROL AND QUALITY ASSURANCE?


QA→
o It ensures the prevention of defects in the process used to make s/w application.
o It involves in process-oriented activities.
o Aim to prevent defect.
o Eg:- verification
o It is the technique of managing the quality.
o All team members are responsible for QA.
o QA is responsible for SDLC.
o It is a process to create the deliverables.
QC→
o It executes the program or code to identify the defects in the s/w application.
o It involves in product-oriented activities.
o Aim to identify and improve.
o Eg:- validation
o It is a method to verify the quality.
o Testing team is responsible for QC.
o QC is responsible for STLC.
o It is a process to verify that deliverables.

4. WHAT IS SDLC?
Manual testing interview question

Ans. Software Development Life Cycle refers to all the activities that are performed
during software development, including - requirement analysis, designing,
implementation, testing, deployment and maintenance phases.

5. EXPLAIN STLC - Software Testing life cycle.


Software testing life cycle refers to all the activities performed during testing of a software
product. The phases include-

• Requirement analyses and validation - In this phase the requirements documents are
analysed and validated and scope of testing is defined.
• Test planning - In this phase test plan strategy is defined, estimation of test effort is
defined along with automation strategy and tool selection is done.
• Test Design and analysis - In this phase test cases are designed, test data is prepared and
automation scripts are implemented.
• Test environment setup - A test environment closely simulating the real world
environment is prepared.
• Test execution - The test cases are prepared, bugs are reported and retested once
resolved.
• Test closure and reporting - A test closure report is prepared having the final test results
summary, learning and test metrics.

6. WHAT IS DYNAMIC TESTING?


It involves in the execution of code. It validates the output with the expected outcome.

7. WHAT IS STATIC TESTING?


It involves in reviewing the documents to identify the defects in the early stages of SDLC.

8. WHAT IS WHITE BOX TESTING?


o This also called as glass-box testing, clear-box and structural testing.
o It is based on applications internal code structure.
o In this, an internal perspective of the system, as well as programming skills are used to
design test cases.
o In white box testing, the tester analyses the internal architecture of the system as well as
the quality of source code on different parameters like code optimization, code coverage,
code reusability etc.
o This testing usually was done at the unit level.

9. WHAT IS BLACK BOX TESTING?


o It is a process of testing a system component considering input, output and general
function.
o The tester interact with the system through the interface providing input and validating
the received output.
o It doesn’t require the knowledge of internal program structure.
o In this we test UI & backend (coding/database).
o External actions are performed.

10. WHAT IS POSITIVE AND NEGATIVE TESTING?


Pt→
Manual testing interview question

o It is determine what system supposed to do.


o It helps to check whether the application is justifying the requirements or not.
Nt→
o It is determine what system not supposed to do.
o It helps to find the defects from the s/w.

11. WHAT IS GRAY BOX TESTING?


It is a combination of both black box and white box testing. The tester who works on this
type of testing needs to have access to design documents, this helps to create better test
cases.

12. WHAT IS TEST STRATEGY?


It is a high-level document and usually developed by project manager. It’s a document which
captures the approach on how we go about testing the product and achieve the goals.

13. WHAT IS TEST PLAN?


It is a document which contains the plan for all the testing activities.

14. WHAT IS TEST SCENARIO?


It gives the idea of what we have to test. Or testable part of an application is called TS.

15. WHAT IS TEST CASE?


It is a set of conditions under which tester determines whether an application/ software is
working correctly or not.

16. WHAT IS TEST BED?


An environment configured for testing is called test bed. It consist of hardware, s/w,
network configuration.

17. WHAT IS TEST SUITE?


Collection of test cases.
18. WHAT IS TEST DATA?
It is a document that is basically used to test the s/w program. It is divided into 2
categories:- a) +ve test data which is generally gives to system to generate the expected
result. b) –ve test data which is used to test the unhandled condition, unexpected ,
exceptional input condition.

19. WHAT IS DEFECT LIFE CYCLE?


Defect Life Cycle or Bug Life Cycle is the specific set of states that a Bug goes through from
discovery to defect fixation.
Bug Life Cycle phases/status:- The number of states that a defect goes through varies from
project to project. Below lifecycle diagram, covers all possible states
o New: When a new defect is logged and posted for the first time. It is assigned a status as
NEW.
o Assigned: Once the bug is posted by the tester, the lead of the tester approves the bug
and assigns the bug to the developer team.
o Open: The developer starts analyzing and works on the defect fix.
Manual testing interview question

o Fixed: When a developer makes a necessary code change and verifies the change, he or
she can make bug status as "Fixed."
o Pending retest: after fixing the defect the developer gives a particular code for retesting
the code to the tester. Here the testing is pending on the testers end, the status assigned
is "pending request."
o Retest: Tester does the retesting of the code at, to check whether the defect is fixed by
the developer or not and changes the status to "Re-test."

• Verified: The tester re-tests the bug after it got fixed by the developer. If there is no bug
detected in the software, then the bug is fixed and the status assigned is "verified."
• Reopen: If the bug persists even after the developer has fixed the bug, the tester
changes the status to "reopened". Once again the bug goes through the life cycle.
• Closed: If the bug is no longer exists then tester assigns the status "Closed."
• Duplicate: If the defect is repeated twice or the defect corresponds to the same concept
of the bug, the status is changed to "duplicate."
• Rejected: If the developer feels the defect is not a genuine defect then it changes the
defect to "rejected."
• Deferred: If the present bug is not of a prime priority and if it is expected to get fixed in
the next release, then status "Deferred" is assigned to such bugs
• Not a bug: If it does not affect the functionality of the application then the status assign
to a bug is "Not a bug".

• New - A bug or defect when detected is in New state


• Assigned - The newly detected bug when assigned to the corresponding developer is in
Assigned state
• Open - When the developer works on the bug, the bug lies in Open state
• Rejected/Not a bug - A bug lies in rejected state in case the developer feels the bug is not
genuine
• Deferred - A deferred bug is one, fix of which is deferred for some time(for the next
releases) based on urgency and criticality of the bug
• Fixed - When a bug is resolved by the developer it is marked as fixed
• Test - When fixed the bug is assigned to the tester and during this time the bug is
marked as in Test
• Reopened - If the tester is not satisfied with issue resolution the bug is moved to
Reopened state
• Verified - After the Test phase if the tester feels bug is resolved, it is marked as verified
• Closed - After the bug is verified, it is moved to Closed status.
Manual testing interview question

20. WHAT IS SMOKE AND SANITY TESTING?


SMOKE→
o It is a kind of Software Testing performed after software build to ascertain that the critical
functionalities of the program are working fine.
o The purpose is to reject a badly broken application so that the QA team does not waste
time installing and testing the software application.
o In Smoke Testing, the test cases chose to cover the most important functionality or
component of the system. The objective is not to perform exhaustive testing, but to verify
that the critical functionalities of the system are working fine.
SANITY→
o Sanity testing is a kind of Software Testing performed after receiving a software build,
with minor changes in code, or functionality, to ascertain that the bugs have been fixed and
no further issues are introduced due to these changes.

Smoke Testing Vs Sanity Testing - Key Differences


Smoke Testing Sanity Testing

Smoke Testing is performed to ascertain that Sanity Testing is done to check the new
the critical functionalities of the program is functionality/bugs have been fixed
working fine

The objective of this testing is to verify the The objective of the testing is to verify the
"stability" of the system in order to proceed "rationality" of the system in order to
with more rigorous testing proceed with more rigorous testing

This testing is performed by the developers Sanity testing is usually performed by testers
or testers

Smoke testing is usually documented or Sanity testing is usually not documented and
scripted is unscripted

Smoke testing is a subset of Acceptance Sanity testing is a subset of Regression


testing Testing

Smoke testing exercises the entire system Sanity testing exercises only the particular
from end to end component of the entire system

Smoke testing is like General Health Check Sanity Testing is like specialized health check
Up up

21. WHAT IS EXIT AND ENTRY CRITERIA?


ENTRY→
It describes when to start testing i.e. what we have to test it should be stable enough to test.
Ex:- if we want to test home page, the SRS/BRS/FRS document & the test cases must be
ready and it should be stable enough to test.
EXIT→
It describes when to stop testing i.e. once everything mentioned below is fulfilled then s/w
release is known as exit criteria:-
a. Followed before actually releasing the s/w to client. Checking computer testing is done
or not.
Manual testing interview question

b. Documents checking:- test matrix (RTM)/summary reports.


SUSPENSION CRITERIA→ when to stop testing temporarily.

22. WHAT IS BLOCKER?


Ans. A blocker is a bug of high priority and high severity. It prevents or blocks testing of
some other major portion of the application as well.

23. WHAT IS REGRESSION TESTING?


To test whether the changed component has introduced any error to unchanged component
or not is called as regression testing. It is perform on QA/production site depends.

24. WHAT IS RETESTING?


To test whether the reported bug has been resolved by the developer team or not, is known
as retesting.

25. MONKEY/AD-HOC TESTING?


It is an informal testing performed without a planning or documentation and without having
knowledge of the applications/software functionalities. Monkey testing is a type of testing
that is performed randomly without any predefined test cases or test inputs.

26. SEVERITY AND PRIORITY?


Priority→
o “How prior we need to fix the bug is priority.”
o It means the occurrences of defect.
o Decide by developer team. Types(low, medium, high, critical)
SEVERITY→
o “How severe the bug is severity”.
o It means how bad the defect is and what impact it can cause in our application.
o Decide by the testing team. Types(minor, medium, major)
27. What is defect priority?
Ans. A defect priority is the urgency of the fixing the defect. Normally the defect priority is
set on a scale of P0 to P3 with P0 defect having the most urgency to fix.

28. What is defect severity?


Ans. Defect severity is the severity of the defect impacting the functionality. Based on the
organisation, we can have different levels of defect severity ranging from minor to critical or
show stopper.

29. Give an example of Low priority-Low severity, Low priority-High severity, High
priority-Low severity, High priority-High severity defects.

1. Low priority-Low severity - A spelling mistake in a page not frequently navigated by


users.
2. Low priority-High severity - Application crashing in some very corner case.
3. High priority-Low severity - Slight change in logo color or spelling mistake in company
name.
4. High priority-High severity - Issue with login functionality.
Manual testing interview question

30. WHAT IS UNIT TESTING?


It is also called as module testing /component testing.
It is done to check whether the individual unit or module of the source code is working
properly. It is done by the developer.

31. INTEGRATION TESTING?


It is a process of testing the interface between the two s/w units.
It is done by 3 ways:- big-bang , top-down, bottom-up approach.
Process of combining & testing multiple components together.
Normally done by developer but a tester can also perform if he has the knowledge of coding.

32. SYSTEM TESTING?


It is a black box testing technique performed to evaluate the computer system. It include
both functional and non-functional testing. Verifying the completed system to ensure that
the application works as intended or not.
“The behaviour of the system is tested as defined by the scope of the development project”.
Carried out by specialist tester/independent tester.

33. USER-ACCEPATANCE TESTING?


User-requirement testing is done.
Done by client as well as end user.
It is a final stage of testing before used.

34. ALPHA-BETA TESTING?


Alpha→
o Developer records all the issues.
o Done by the end user at dev site. (involves client or tester+dev)
Beta→
o Dev go through all the issues after specific period of time.
o Done by the end user at the client site. (involves client/user)

35. HOW MONKEY TESTING IS DIFFERENT FROM ADHOC TESTING?


In case of adhoc testing although there are no predefined or documented test cases still
testers have the understanding of the application. While in case of monkey testing testers
doesn't have any understanding of the application.

36. Explain Agile methodology?


Agile methodology of software development is based on interative and incremental
approach. In this model, the application is broken down into smaller build on which
different cross functional team work together providing rapid delivery along with adapting
to changing needs at the same time.
o Working is done by individual person.
o There is scrum master, who will be either tester/developer from the team or the person
who has the knowledge of both testing and coding.
o Responsibility of scrum master is to narrating the stories to both the team i.e. testing
team and development team.
o Scrum meetings can be happen in once a week or in 15 days or once a month. Most of
the time client is included in scrum meeting.
Manual testing interview question

o Because of this meeting, if the one person is absent the another person from same team
can complete his work. So project isn’t paused and dependency on one person is not
happened. This is the main advantage of this model.
o Sprint is dividing the project into modules and distributing these modules among both
the team’s so that the team is working parallelly.
o When to use:- when the project is big/medium and we have to deliver it as soon as
possible then we will use this model. Quality is maintained.

37. What is scrum?


A scrum is a process for implementing Agile methodology. In scrum, time is divided into
sprints and on completion of sprints, a deliverable is shipped.

38. What are the different roles in scrum?


Ans. The different roles in scrum are -

1. Product Owner - The product owner owns the whole development of the product, assign
tasks to the team and act as an interface between the scrum team(development team)
and the stakeholders.
2. Scrum Master - The scrum master monitors that scrum rules get followed in the team
and conducts scrum meeting.
3. Scrum Team - A scrum team participate in the scrum meetings and perform the tasks
assigned.

39. What is a scrum meeting?


A scrum meeting is daily meeting in scrum process. This meeting is conducted by scrum
master and update of previous day's work along with next day's task and context is defined
in this meeting.

40. Explain TDD (Test Driven Development).


Test Driven Development is a software development methodology in which the
development of the software is driven by test cases created for the functionality to be
implemented. In TDD, first the test cases are created and then code to pass the tests is
written. Later the code is refactored as per the standards.

41. Explain equivalence class partitioning.


Equivalence class partitioning is a specification based black box testing techniques. ECP
means Grouping test data into equivalence classes with the assumpation that all the data
items lying in the classes will have same effect on the application. In simple it means diving
any module into equal parts and test the each part separately. E.g. 1 :- for testing a Square
program(program that prints the square of a number- the equivalence classes can be:-Set of
Negative numbers, whole numbers, decimal numbers, set of large numbers etc.)
2 :- suppose we have to test 1-100 no’s. So 1st we will divide this no into 5 equal parts. (Like
1-20, 21-40,41-60,61-80,81-100). Now we will select random 3 values and multiply these
values with the no of parts. Whatever the no will be, we will checked for that values from all
the module in place of checking 100 values.
Purpose:- testing a complete module is exhaustive testing and time consuming that’s why
we use quivalence partioning as it is time saving.

42. What is boundary value analysis?


Boundary value analysis is a software testing technique for designing test cases wherein the
boundary values of the classes of the equivalence class partitioning are taken as input to the
Manual testing interview question

test cases. It is also called as a part of stress and –ve testing. e.g. if the test data lies in the
range of 0-100, the boundary value analysis will include test data - 0,1, 99, 100.
43. WHAT ARE SOME DEFECT REPORTING ATTRIBUTES?
Ans. Some of the attributes of a Defect resport are-
DefectId - A unique identifier of the defect.
Defect Summary - A one line summary of the defect, more like a defect title.
Defect Description - A detailed description of the defect.
Steps to reproduce - The steps to reproduce the defect.
Expected Result - The expected behaviour from which the application is deviating because of
the defect.
Actual Result- The current erroneous state of the application w.r.t. the defect.
Defect Severity - Based on the criticality of the defect, this field can be set to minor, medium,
major or show stopper.
Priority - Based on the urgency of the defect, this field can be set on a scale of P0 to P3.

44. What is stub?


Ans. In case of top-down integration testing, many a times lower level modules are not
developed while beginning testing/integration with top level modules. In those cases
Stubs or dummy modules are used that simulate the working of modules by providing
hardcoded or expected output based on the input values.

45. What is driver?


Ans. In case of bottom-up integration testing, drivers are used to simulate the working of
top level modules in order to test the related modules lower in the hierarchy.

46. What are some advantages of automation testing?


Ans. Some advantages of automation testing are-
Test execution using automation is fast and saves considerable amount of time.
Carefully written test scripts remove the chance of human error during testing.
Tests execution can be scheduled for nightly run using CI tools like Jenkins which can also
be configured to provide daily test results to relevant stakeholders.
Automation testing is very less resource intensive. Once the tests are automated, test
execution requires almost no time of QAs. Saving Qa bandwidth for other explratory tasks.

47. What are some disadvantages of automation testing?


Ans. Some advantages of automation testing are-
It requries skilled automation testing experts to write test scritps.
Additional effort to write scripts is required upfront.
Automation scripts are limited to verification of the tests that are coded. These tests may miss
some error that is very glaring and easily identifiable to human(manual QA).
Even with some minor change in application, script updation and maintenance is required

Verification strategies/error guessing/sdlc/white box techniques/exhaustive testing/v


model/spiral model/non-functional testing
Manual testing interview question
Manual Testing Questions &Answers for Freshers

1. Explain what is software testing.

Ans - It is the process of analysing any given piece of software to determine if it meets
shareholders’ needs as well as detecting defects, and ascertaining the item’s overall quality
by measuring its performance, features, quality, utility, and completeness. Bottom line, it’s
quality control.

2. What is quality control, and how does it differ from quality assurance?

Ans - Quality control is the process of running a program to determine if it has any defects,
as well as making sure that the software meets all of the requirements put forth by the
stakeholders. Quality assurance is a process-oriented approach that focuses on making sure
that the methods, techniques, and processes used to create quality deliverables are applied
correctly.

3. What exactly is manual software testing, and how does it differ from automated software
testing?

Ans- Manual software testing is a process where human testers manually run test cases,
then generate the resulting test reports. With automation software testing, these functions
are executed by automation tools such as test scripts and code. The tester takes the end
user’s role to determine how well the app works.

4. What are the advantages of manual testing?

Ans - Manual testing’s strengths are:

It’s cheaper

You get visual feedback that’s accurate and quick

It’s ideal for testing minor changes

It’s perfect for ad hoc testing

Testers don’t have to know anything about automation tools

It’s great for testing UI’s


5. On the other hand, what are the drawbacks to manual testing?

Ans - Manual testing’s weaknesses are:

Susceptible to human error

Some tasks may be difficult to accomplish manually, requiring more time to complete

The cost adds up, so it’s more expensive in the long run

You cannot record the manual testing process, so it’s hard to replicate it.

6. What kind of skills are needed for someone to become a software tester?

Ans - Software testers need skills such as:

Problem-solving skills

Excellent written and verbal communication skills

Detail-oriented

Able to handle the pressure

Can work solo or as a team member equally well

Organizational skills

Related technical skills

7. Explain what is SDLC.

Ans - This is an acronym for Software Development Life Cycle and encompasses all of the
stages of software development, including requirement gathering and analysis, designing,
coding, testing, deployment, and maintenance.

8. What is a test case?

Ans - Test case is used to check whether an application complies with its requirements. It is
a documented set of circumstances including prerequisites, input values, and expected
outcomes.

9. What is a test scenario?

Ans - A test scenario is derived from a use case. It's used to test an application's feature
from beginning to end. Multiple test cases can be accommodated by a single test scenario.
When there is a time constraint during testing, scenario testing comes in handy.
10. What is a test plan?

Ans - A test plan is a formal document that specifies the scope of testing, the method to be
used, the resources needed, and the estimated time to complete the testing process. It is
derived from the specifications (Software Requirement Specifications).

11. What is test data?

Ans - Test data is information that is used to test software with various inputs and
determine whether the resulting output matches the intended result. This data is generated
based on the needs of the company.

12. What is a test script?

Ans - An automated test case created in any programming or scripting language is known as
a test script. These are essentially a collection of instructions for evaluating an application's
functionality.

13. What types of manual testing are there? Break them down.

Ans - Manual testing is broken down into:

Black Box

White Box

Integration

Unit

System

Acceptance

14. What is black box testing, and what are the various techniques?

Ans -Software testers employ black-box testing when they do not know the internal
architecture or code structure. The techniques are-

Equivalence Partitioning

Boundary value analyse & Cause-eff


15. What is white box testing ?

Ans - Unlike black-box testing, white box involves analysing the system’s internal
architecture and/or its implementation, in addition to its source code quality.

16. White box testing various techniques?

Ans - It’s techniques are:

Statement Coverage

Decision Coverage

17. What’s the difference between verification and validation?

Ans - Verification evaluates the software at the development phase, ascertaining whether or
not a product meets the expected requirements. On the other hand, validation evaluates
the software after the development phase, making it sure it meets the requirements of the
customer.

18. What’s a testbed?

Ans - It’s not furniture. A testbed is an environment used for testing an application,
including the hardware as well as any software needed to run the program to be tested.

19. What is Sanity testing?

Ans - Sanity testing is testing done at the release level to test the main functionalities. It’s
also considered an aspect of regression testing.

20. When should developers implement configuration management procedures?

Ans - This should be done during test planning.

21. List the four different test levels

Ans - The four levels are:

Unit/component/program/module testing

Integration testing
System testing

Acceptance testing

22. What’s the difference between a bug and a defect?

Ans - A bug is a fault in the software that’s detected during testing time, while a defect is a
variance between expected results and actual results, detected by the developer after the
product goes live.

23. What about the difference between an error and a failure?


23. What about the difference between an error and a failure?
Ans - If a program can’t run or be compiled during development, it’s an error. If an end-user
discovers an issue with the software, it’s a failure.

24. What’s GUI testing?

Ans -This tests the interface between the software and the end-user. Short for Graphics
User Interface.

25. When should testing end?

Ans - There are a few criteria for ending testing:

The bug rate has fallen below an agreed-upon level

The testing or release deadlines have arrived

The testing budget is out of funds

A certain percentage of test cases have passed

The alpha or beta testing periods have ended

Code, functionality, or requirements coverage have been met at a declared point

These were some basic manual testing interview questions. In the coming section, we bring
to you some advanced level manual testing interview questions.

26. What are the different types of Software testing?

Ans - Software testing is classified into two main categories.

Functional testing & Non-Functional testing


27. Explain Functional Testing

Ans - Functional testing is a type of black-box testing. It focuses on the software's functional
requirements rather than its internal implementation. A functional requirement refers to
the system's needed behaviour in terms of input and output.

It checks the software against the functional requirements or specification, ignoring non-
functional characteristics like performance, usability, and dependability.

The purpose of functional testing is to ensure that the software up to snuff in terms of
functionality and to solve the difficulties of its target users.

Some of the types of functional Testing are -

Unit Testing

Integration Testing

Regression Testing

System Testing

Smoke Testing

Performance Testing

Stress Testing

28. Explain Non functional testing

Ans - Non-functional testing examines the system's non-functional requirements, which are
characteristics or qualities of the system that the client has specifically requested.
Performance, security, scalability, and usability are among them.

Functional testing is followed by non-functional testing. It examines aspects that are


unrelated to the software's functional requirements. Non-functional testing assures that the
programme is safe, scalable, and fast, and that it will not crash under excessive pressure.

29. Mention a few advantages of Automated testing.

Ans - The following are some major advantages of automated testing -

Automated test execution is quick and saves a significant amount of time.

Human mistakes are eliminated during testing when test scripts are carefully prepared.

CI tools like Jenkins, which may also be set to distribute daily test results to key
stakeholders, can be used to schedule test execution for a nightly run.
Automation testing uses a lot less resources. Test execution requires nearly no time from
QAs once the tests have been automated. QA bandwidth can be used for other exploratory
work.

30. What is Regression Testing?

Ans - Regression Testing is a full or partial selection of already executed test cases that are
re-executed to ensure existing functionalities work fine.

Steps involved are -

Re-testing: All of the tests in the current test suite are run again. It turns out to be both
pricey and time-consuming.

Regression tests are divided into three categories: feature tests, integration tests, and end-
to-end testing. Some of the tests are chosen in this step.

Prioritization of test cases: The test cases are ranked according to their business impact and
important functionalities.

31. What is Test Harness?

Ans - A test harness is a collection of software and test data used to put a programme unit
to the test by running it under various conditions such as stress, load, and data-driven data
while monitoring its behaviour and outputs.

32. Differentiate between Positive and Negative Testing

Ans -Positive Testing

Negative Testing

Positive testing ensures that your software performs as expected. The test fails if an error
occurs during positive testing.

Negative testing guarantees that your app can gracefully deal with unexpected user
behaviour or incorrect input.

In this testing, the tester always looks for a single set of valid data.

Testers use as much ingenuity as possible when validating the app against erroneous data.
33. What is a Critical Bug?

Ans - A critical bug is one that has the potential to affect the bulk of an application's
functioning. It indicates that a significant portion of functionality or a critical system
component is utterly broken, with no way to proceed. The application cannot be delivered
to end users until the critical bug has been fixed.

34. What is Test Closure?

Ans -Test Closure is a document that summarises all of the tests performed throughout the
software development life cycle, as well as a full analysis of the defects fixed and errors
discovered. The total number of experiments, the total number of experiments executed,
the total number of flaws detected, the total number of defects settled, the total number of
bugs not settled, the total number of bugs rejected, and so on are all included in this memo.

35. Explain the defect life cycle.

Ans -A defect life cycle is a process by which a defect progresses through numerous stages
over the course of its existence. The cycle begins when a fault is discovered and concludes
when the defect is closed after it has been verified that it will not be recreated.

36. What is the pesticide paradox? How to overcome it?

Ans - According to the pesticide paradox, if the same tests are done repeatedly, the same
test cases will eventually stop finding new bugs. Developers will be especially cautious in
regions where testers discovered more flaws, and they may over look Positive and Negative
Testing?

other areas. Methods for avoiding the pesticide conundrum include:

To create a completely new set of test cases to put various aspects of the software to the
test.

To create new test cases and incorporate them into existing test cases.

It is possible to detect more flaws in areas where defect levels have decreased using these
methods.

37. What is API testing?

Ans - API testing is a sort of software testing that entails evaluating application
programming interfaces (APIs) to see if they meet functionality, reliability, performance, and
security requirements. Simply put, API testing is designed to detect defects, inconsistencies,
or departures from an API's expected behaviour. Typically, applications are divided into
three layers:

The user interface is also known as the presentation layer.

For business logical processing, the Business Layer or application user interface is used.

API testing is done at the most vital and important layer of software architecture, the
Business Layer, for modelling and manipulating data.

38. What is System testing?

Ans -System testing is a type of testing in which the entire software is tested. System testing
examines the application's compliance with its business requirements.

39. What is Acceptance testing?

Ans - Acceptance testing is a type of testing done by a possible end-user or customer to see
if the software meets the business requirements and can be used.

40. Differentiate between bug leakage and bug release

Ans - Bug Leakage - When tested software is pushed into the market and the end-user
discovers defects, this is known as bug leakage. These are bugs that the testing team
overlooked throughout the testing phase.

Bug Release - When a certain version of software is launched into the market with some
known bugs that are expected to be fixed in later versions, this is known as a bug release.
These are low-priority issues that are highlighted in the release notes when sharing with
end-users.

41. What do you mean by Defect Triage?

Ans -Defect triage is a procedure in which defects are prioritised depending on a variety of
characteristics such as severity, risk, and the amount of time it will take to fix the fault. The
defect triage meeting brings together several stakeholders - the development team, testing
team, project manager, BAs, and so on – to determine the order in which defects should be
fixed.

42. What is Integration Testing? What are its types?


Ans -Integration testing is performed after unit testing. We test a group of linked modules in
integration testing. Its goal is to identify faults with module interaction.

The following are the types of integration testing -

Big Bang Integration Testing — After all of the modules have been merged, big bang
integration testing begins.

Top-down Integration Testing — In top-down integration, testing and integration begin at


the top and work their way down.

Bottom-up Integration Testing — In bottom-up integration testing, lower-level modules are


tested before moving up the hierarchy to higher-level modules.

Hybrid Integration Testing — Hybrid integration testing combines top-down and bottom-up
integration testing techniques. The integration with this approach starts at the middle layer,
and testing is done in both directions.

43. What is a stub?

Ans - Many times, when top-down integration testing is performed, lower-level modules are
not produced until top-level modules are tested and integrated. Stubs or dummy modules
are used in these circumstances to emulate module behaviour by delivering a hard-coded or
predicted result based on the input variables.

44. What is code coverage?

Ans - The quantity of code covered by the test scripts is referred to as code coverage. It
conveys the scope of the test suite's coverage of the application.

45. What is a cause-effect graph?

Ans - A cause-effect graph testing technique is a black-box test design technique that uses a
graphical representation of the input (cause) and output (effect) to construct the test. This
method employs a variety of notations to describe AND, OR, NOT, and other relationships
between the input and output conditions.

46. Explain equivalence class partitioning.

Ans - Equivalence class partitioning is a black-box testing technique based on specifications.


A set of input data that defines multiple test conditions is partitioned into logically
comparable groups in equivalence class partitioning, so that utilising even a single test data
from the group for testing can be considered as similar to using all the other data in that
group.

47. What is boundary value analysis?

Ans -The border values of the classes of the equivalence class partitioning are used as input
to the test cases in boundary value analysis, which is a software testing technique for
designing test cases.

48. What is your approach towards a severely buggy program? How would you handle it?

Ans - In such cases, the best course of action is for testers to go through the process of
reporting any flaws or blocking-type issues that arise, with an emphasis on critical bugs.
Because this sort of crisis might result in serious issues such as insufficient unit or
integration testing, poor design, wrong build or release methods, and so on, management
should be contacted and given documentation as proof of the problem.

49. What if an organization's growth is so rapid that standard testing procedures are no
longer feasible? What should you do in such a situation?

Ans -This is a very prevalent issue in the software industry, especially with the new
technologies that are being used in product development. In this case, there is no simple
answer; however, you could:

Hire people who are good at what they do.

Quality issues should be ‘fiercely prioritised' by management, with a constant focus on the
client.

Everyone in the company should understand what the term "quality" implies to the end-
user.

50. When can you say for sure that the code has met its specifications?

Ans - Most businesses have coding "standards" that all developers are expected to follow,
but everyone has their own opinion on what is best, as well as how many regulations are
too many or too few. There are many methods available, such as a traceability matrix, to
guarantee that requirements are linked to test cases. And when all of the test cases pass,
that means the code satisfies the requirement.

You might also like