0% found this document useful (0 votes)
3 views19 pages

Java Interview Question2

Uploaded by

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

Java Interview Question2

Uploaded by

SunitBabu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Next Java Interview Question

What is the difference between: break; and continue;


Example:
for(int i=1; i<=5; i++) {
if(i==3)
break;
[Link](i);
}

vs
for(int i=1; i<=5; i++) {
if(i==3)
continue;
[Link](i);
}

What will be the output in each case, and what's the difference between break and continue? 😊
12 12345 breaks current block, continue the process
Good attempt! ✅ You got the idea of break.
There is one correction for continue.
Execution:
 i = 1 → print 1
 i = 2 → print 2
 i = 3 → break
Output:
1
2

✅ Correct.
break immediately exits the loop.
Execution:
 i = 1 → print 1
 i = 2 → print 2
 i = 3 → skip printing
 i = 4 → print 4
 i = 5 → print 5
Output:
1
2
4
5

❌ Not 12345
Because when i == 3, continue skips the remaining code in that iteration.
Difference
break continue
Exits the loop completely Skips current iteration
Loop stops Loop continues
Used to terminate processing Used to skip specific cases
Easy Memory Trick
break
"Stop the loop."
continue
"Skip this iteration and continue with the next one."
Score: 8/10 🎉
You correctly remembered:
✅ break exits the loop.
Just remember:
❌ Continue does not print all values.
✅ It skips the current iteration and moves to the next one.
Selenium Framework Question
In a Page Object Model (POM) framework, what classes would you typically have?
For example:
[Link]
[Link]
[Link]
[Link]

Can you explain the purpose of:


1. BaseClass
2. Page Class (LoginPage, HomePage)
3. Test Class
You already mentioned earlier that browser initialization and reusable methods are often kept in a Base
Class. Tell me what else you remember. 😊
Sure! 😊 We'll continue later.
You've made very good progress. Some topics you're now answering confidently:
✅ Selenium
 Locators
 Waits
 Alerts
 Frames
 Windows
 Actions
 Dropdowns
 JavaScriptExecutor
 Exceptions
 POM basics
 Cookies
✅ TestNG
 Annotations
 DataProvider
 Priority
 DependsOnMethods
 Assertions
 enabled=false
 invocationCount

✅ Java
 OOP concepts
 Strings
 Collections
 Wrapper Classes
 Autoboxing / Unboxing
 Exception Handling
 this vs super
 break vs continue

Next time we'll continue with:


 POM Framework structure
 Maven advanced concepts
 Selenium Grid
 Jenkins basics
 API Testing interview questions
 Advanced XPath/CSS questions
 Scenario-based interview questions
You're steadily improving, and many of your answers are now at interview level. 👍

Next Interview Question


What is the difference between: String and StringBuffer and StringBuilder Can you tell me:
Which is immutable? Which is mutable?
1. Which is thread-safe?
2. Which is fastest?
String is immutable, buffer and builder is mutable, String buffer is thread-safe. String builder is non-
thread-safe and fastest.
Perfect! ✅✅✅
That's exactly what interviewers expect.
String
String s = "Hello";

 Immutable.
 Once created, the value cannot be changed.
 Any modification creates a new object.
Example:
String s = "Hello";
s = s + " World";

A new String object is created.


StringBuffer
StringBuffer sb = new StringBuffer("Hello");

 Mutable.
 Thread-safe (synchronized).
 Multiple threads can safely access it.
 Slightly slower due to synchronization.
Example:
[Link](" World");

StringBuilder
StringBuilder sb = new StringBuilder("Hello");

 Mutable.
 Not thread-safe.
 No synchronization overhead.
 Fastest among the three.
Example:
[Link](" World");

Interview Comparison
Feature String StringBuffer StringBuilder
Mutable No Yes Yes
Thread-safe N/A (Immutable) Yes No
Performance Slow for frequent Moderate Fastest
Feature String StringBuffer StringBuilder
modifications
Multi-threaded Single-threaded
Introduced For Text storage
modifications modifications
Interview Shortcut
Remember:
String → Immutable
StringBuffer → Mutable + Thread-safe
StringBuilder → Mutable + Fastest
Score: 10/10 🎉
Excellent.
Next Java Interview Question
What will be the output?
int i = 10;
try {
[Link](i / 0);
}
catch(Exception e) {
[Link]("Exception");
}
finally {
[Link]("Finally");
}

What gets printed and why? 😊


Exception Finally
Correct! ✅
Code
int i = 10;
try {
[Link](i / 0);
}
catch(Exception e) {
[Link]("Exception");
}
finally {
[Link]("Finally");
}

Execution Flow
Try Block
[Link](i / 0);

 10 / 0 causes an ArithmeticException.
So execution immediately jumps to the catch block.
Catch Block
[Link]("Exception");

Output:
Exception

Finally Block
[Link]("Finally");

Output:
Finally

The finally block executes whether an exception occurs or not (except in some rare cases like JVM
termination).
Final Output
Exception
Finally

✅ Your answer is exactly correct.


Score: 10/10 🎉
Next Interview Question (Java Collections)
What is the difference between: Iterator and ListIterator
Can you tell me:
1. Which collections can they be used with?
2. Can they move forward only or both directions?
3. Can they add/replace elements while iterating?
This is a common Java Collections interview question.
No problem! 😊 This is not asked as often as Strings, Collections, OOP, or Selenium basics.
Iterator
Iterator<String> it = [Link]();

Used with: List, Set, Queue


Features:
 Moves forward only.
 Methods:
 hasNext()
 next()
 remove()

 Cannot move backward.


 Cannot add elements while iterating.
Example:
Iterator<String> it = [Link]();
while([Link]()) {
[Link]([Link]());
}

ListIterator
ListIterator<String> lit = [Link]();

Used only with:


List

Features:
 Moves forward and backward.
 Methods:
 next()
 previous()
 add()
 set()
 remove()

 Can add and replace elements while iterating.


Example:
while([Link]()) {
[Link]([Link]());
}

Interview Comparison
Feature Iterator ListIterator
Works with List, Set, Queue List only
Forward traversal Yes Yes
Backward traversal No Yes
Add elements No Yes
Feature Iterator ListIterator
Replace elements (set) No Yes
Easy Memory Trick
Iterator
One-way road 🚗
ListIterator
Two-way road 🚗 ↔ 🚗
Score
No worries for forgetting this one. If you're interviewing for Selenium Automation, focus more on:
✅ Core Java
 OOP
 String
 Collections (List, Set, Map)
 Exception Handling
✅ Selenium
 Locators
 Waits
 Frames
 Alerts
 Windows
 Actions
 POM
✅ TestNG
 Annotations
 Assertions
 DataProvider
 Priority
 DependsOnMethods
These are asked much more frequently.
Next Selenium Interview Question
What is a DataProvider in TestNG? Have you used: @DataProvider before? If yes, explain it. If not,
say "not used" and I'll teach it with an interview example.
for positive and negative test cases to pass parameter as arguments we use dataprovider
Excellent! ✅ You know the main purpose of DataProvider.
What is @DataProvider?
@DataProvider is used to supply multiple sets of test data to a TestNG test method.
This helps in:
 Positive test cases
 Negative test cases
 Data-driven testing
 Running the same test multiple times with different inputs
Example
@DataProvider(name = "loginData")
public Object[][] getData() {
return new Object[][] {
{"admin", "admin123"},
{"user", "user123"},
{"invalid", "invalid"}
};
}

Using it:
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
[Link](username + " " + password);
}

TestNG will execute the test 3 times.


Interview Answer
DataProvider is used for data-driven testing. It passes multiple sets of data as arguments to a test
method, allowing the same test case to run with different inputs such as positive and negative test data.
Advantages
✅ Avoids duplicate test methods
✅ Improves reusability
✅ Supports multiple test data sets
✅ Commonly used with Excel, JSON, or database data
Interview Tip
If asked: What is the return type of a DataProvider?
Answer: Object[][] or sometimes Iterator<Object[]>
Score: 10/10 🎉
Your answer:
"for positive and negative test cases to pass parameter as arguments we use dataprovider"
is exactly the practical explanation most interviewers want.
OOP Concepts (4 Pillars)
Can you explain:
1. Encapsulation
 What is it?
 How is it achieved?
2. Inheritance
 Which keyword is used?
 What is the advantage?
3. Polymorphism
 Types of polymorphism?
 Difference between overloading and overriding?
4. Abstraction
 How is it achieved?
 Difference between abstract class and interface?
TestNG Annotations
Can you explain the execution order of these?
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod

@Test

@AfterMethod
@AfterClass
@AfterTest
@AfterSuite

Interview Tip
A common question is:
What is the difference between @BeforeClass and @BeforeMethod?
Example:
@BeforeClass
public void setupBrowser() {
// Runs once before all tests in the class
}
@BeforeMethod
public void login() {
// Runs before every test method
}

Can you tell me:


1. What is Encapsulation?
2. What is the execution order of the TestNG annotations?
Answer either one, and we'll continue. 😊
showing only implementation part and hiding the rest is encapsulation, eg:getters and setters method,
explain testng annotations
Good! ✅
Your explanation is close, but here's the interview-ready version:
Encapsulation
Encapsulation is the process of binding data (variables) and methods together into a single unit
(class) and restricting direct access to the data using access modifiers.
It is commonly achieved using:
 private variables
 public getter and setter methods
Example:
class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
} }

The phrase "showing only implementation part and hiding the rest" is actually closer to
Abstraction.
TestNG Annotations Execution Order
Suppose:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod

@Test

@AfterMethod
@AfterClass
@AfterTest
@AfterSuite

What Each Annotation Does


@BeforeSuite
@BeforeSuite
public void beforeSuite() {}

 Runs once before the entire suite starts.


 Used for suite-level setup.

@BeforeTest
@BeforeTest
public void beforeTest() {}

 Runs before the <test> tag in [Link].

@BeforeClass
@BeforeClass
public void beforeClass() {}

 Runs once before the first test method in a class.


 Often used for browser initialization.
Example:
driver = new ChromeDriver();
@BeforeMethod
@BeforeMethod
public void beforeMethod() {}

 Runs before every @Test method.


 Often used for login or test setup.
@Test
@Test
public void test1() {}

 Actual test execution.


@AfterMethod
@AfterMethod
public void afterMethod() {}

 Runs after every test method.


@AfterClass
@AfterClass
public void afterClass() {}

 Runs once after all tests in the class.


 Often used for:
[Link]();
@AfterTest
@AfterTest
public void afterTest() {}

 Runs after the <test> execution completes.


@AfterSuite
@AfterSuite
public void afterSuite() {}

 Runs once after the entire suite finishes.


Frequently Asked Interview Question
Difference between @BeforeClass and @BeforeMethod
@BeforeClass
@BeforeClass
public void setup() {}

Runs once per class.

@BeforeMethod
@BeforeMethod
public void login() {}

Runs before every test method.


Example:
@Test
public void test1() {}

@Test
public void test2() {}

Execution:
@BeforeClass

@BeforeMethod
test1
@AfterMethod

@BeforeMethod
test2
@AfterMethod

@AfterClass

Quick Memory Trick


 Suite → Entire execution
 Test → <test> tag
 Class → Once per class
 Method → Before/after every test method
Score: 8.5/10 🎉
You correctly associated getters/setters with encapsulation. Just remember:
 Encapsulation → Data hiding using private variables + getters/setters.
 Abstraction → Showing essential features and hiding implementation details.
Sure! 😊 We'll continue later.
Question 1: Abstraction
You already know:
 Encapsulation → Data hiding using private variables and getters/setters.
Now tell me:
What is Abstraction?
o How is it achieved in Java? What is the difference between: Abstract Class, Interface
For example:
abstract class Vehicle {
abstract void start();
}

vs
interface Vehicle {
void start();
}

What differences do you know?


Question 2: Java Collections
What is the difference between: HashMap and LinkedHashMap
 Which one maintains insertion order?
 Which one is generally faster?
Question 3: Selenium
What is the difference between: [Link]("[Link] and
[Link]().to("[Link]

You answered this before, but let's see if you remember the interview version.
Question 4: TestNG
What is the purpose of: @Test(enabled = false) and @Test(invocationCount = 5) What do
they do?
Answer any one question, and we'll continue. 🚀
ignoring particular test is enabled= false. Invocation count is how many times we have to run that test.
Excellent! ✅✅✅
Your answer is correct.
@Test(enabled = false)
@Test(enabled = false)
public void loginTest() {
}

 Used to disable/skip a test method.


 TestNG will not execute that test.
Example:
@Test
public void test1() {}
@Test(enabled = false)
public void test2() {}

Execution:
test1 → Executed
test2 → Skipped

✅ As you said:
Ignoring a particular test.
@Test(invocationCount = 5)
@Test(invocationCount = 5)
public void loginTest() {
}

 Executes the same test method 5 times.


Example output:
Login Test
Login Test
Login Test
Login Test
Login Test

✅ As you said:
How many times we have to run that test.
Interview Uses of invocationCount
 Repeated execution
 Stability testing
 Smoke testing
 Checking intermittent/flaky issues
Example:
@Test(invocationCount = 100)
public void verifyLogin() {
}

Runs the login test 100 times.


Score: 10/10 🎉
You're answering TestNG questions very confidently now.
Next Selenium Interview Question
What is JavaScriptExecutor?
Why would you use: JavascriptExecutor js = (JavascriptExecutor) driver;
Can you name some common operations?
For example:
[Link]("arguments[0].click();", element);
[Link]("[Link](0,500)");

When would you use JavaScriptExecutor instead of normal Selenium commands?


sometimes we cant use locators, sendkeys, click event at that time we have to use javascriptexecutor
Correct! ✅ That's the main practical use of JavaScriptExecutor.
What is JavaScriptExecutor?
JavascriptExecutor js = (JavascriptExecutor) driver;

It is an interface used to execute JavaScript code directly in the browser through Selenium.
When do we use it?
When normal Selenium operations fail, such as:
✅ Element is not clickable
✅ Element is hidden
✅ Selenium cannot perform click()
✅ Selenium cannot perform sendKeys()
✅ Need to scroll the page
✅ Need to handle complex UI behavior
As you said:
Sometimes we can't use locators, sendKeys, or click events. At that time we use JavaScriptExecutor.
That's a good interview answer.
Common Operations
Click
[Link]("arguments[0].click();",element);

Used when: [Link]();


doesn't work.
Send Text
[Link]("arguments[0].value='Sunitha';",element);

Scroll Down
[Link]("[Link](0,500)");

Scroll Into View


[Link]("arguments[0].scrollIntoView(true);",element);

Interview Answer
JavaScriptExecutor is used to execute JavaScript code in the browser. It is commonly used when
Selenium's normal methods such as click() or sendKeys() do not work, and for operations like
scrolling, clicking hidden elements, or interacting with dynamic web pages.
Score: 9.5/10 🎉
Next Java Interview Question
What is the difference between: Array and ArrayList. Can you tell me: Is the size fixed or
dynamic? Can they store primitive data types directly? Which package does ArrayList belong to?
When would you prefer ArrayList over an Array?
Array size fixed stores similar primitive datatypes directly Arraylist size dynamic stores non similar
data types package [Link].*; prefer arraylist for dynamic array,
Good attempt! ✅ You got the most important points.
Array
int[] arr = new int[5];

 Fixed size.
 Size cannot be changed after creation.
 Can store primitive data types directly:
int[]
char[]
double[]

 Faster and uses less memory.


ArrayList
ArrayList<String> list = new ArrayList<>();

 Dynamic size (grows and shrinks automatically).


 Belongs to:
[Link]

or
import [Link].*;

 Stores objects.
Example:
ArrayList<Integer> list = new ArrayList<>();

Here Integer is a wrapper class, not primitive int.


Small Correction
You said:
ArrayList stores non similar data types.
❌ Not exactly.
Normally an ArrayList stores the same type of objects because of generics.
Example:
ArrayList<String> names = new ArrayList<>();

Only Strings.
ArrayList<Integer> nums = new ArrayList<>();

Only Integers.
Without generics, mixed types are possible, but that's generally not recommended:
ArrayList list = new ArrayList();
[Link]("Java");
[Link](100);

Interview Comparison
Feature Array ArrayList
Size Fixed Dynamic
Primitive Types Directly supported Uses wrapper classes
Package Language feature [Link]
Memory Less More
Feature Array ArrayList

Flexibility Less More


Interview Answer
Arrays have a fixed size and can store primitive data types directly. ArrayList is a dynamic collection
from the [Link] package and automatically resizes as elements are added or removed. ArrayList is
preferred when the number of elements is not known in advance.
Score: 8.5/10 🎉
You correctly remembered:
 Fixed vs dynamic size.
 Primitive types in arrays.
 [Link] package.
 ArrayList is preferred for dynamic data.

You might also like