1-27 QUES : BASICS JAVA THEORY
28 OOPS Interview questions - source - Rahul shetty
29 Java interview questions - source - Rahul shetty
30 JAVA _ SK DOCUMENT S1
31 TOP 20 JAVA - TESTLEAF - - SK PDF
*********** ************************** **************1 -27 ques
1 Variables in Java:
A variable is a name used to store a value (like number, text, etc.) in memory.
It allows us to reuse and manipulate the data in our program.
🧠 Example:
int age = 25;
String name = "Sri";
Here, age and name are variables.
2 Data Types in Java:
Data types define what kind of data a variable can hold — like numbers, text, or
true/false.
3 Why int, float, boolean are Primitive Data Types?
Because they are basic, built-in types in Java that store the actual value directly in
memory, not a reference.
int age = 25; → 25 is stored directly
boolean isActive = true; → stores true directly
4 Why String, Array, Object are Non-Primitive Data Types?
Because they are created from classes and store a reference (address) in memory, not
the actual data.
String name = "Sri"; → Java stores a reference to the "Sri" string object in memory.
int[] nums = {1, 2, 3}; → Again, nums holds a reference to the actual array.
5 Example:
String name = "muthu";
What’s happening here?
🔍 Behind the scenes:
"muthu" is a String object stored somewhere in heap memory.
The variable name doesn't store "muthu" directly — it stores the memory address
(reference) of that string.
Think of it like this:
Variable Points to (Reference) Actual Data
Name 🔗 memory address → "muthu" in heap
Primitive: You’re holding the chocolate directly.
Non-Primitive: You're holding a note with the address of where the chocolate
box is kept.
6 Strings can be reused or shared internally (called String Pooling).
In Java, when we write String name = "muthu";, the variable name holds a
reference (or pointer) to the memory where the actual string "muthu" is stored.
This is different from primitive types, which store the value directly.
Using references makes it easy to reuse and manipulate large objects efficiently."
7 what is an array ?
An array is a collection of elements of same data type.
Array is used to store multiple values in a single variable, rather than declaring
separately
int[ ] arr = {1,2,3,4,5,6} //// int arr[ ] = {1,2,3,4,5,6}
arr[2] is ------ 3;
int arr [ ] [ ] = { { 1,2,3 } , { 4,5,6 } } ;
8 What is string ?
A string is a non primitive data type and an object actually that represent a sequence
of characters.
So when declaring string - we can declare it in 2 ways :
--- One is string literal
String s1 = “Sri”;
String s2 = “Sri”;
--- Another type is storing the string using the new memory operator
String s1 = new String (“Sri”);
String s2 = new String (“Sri”);
String name = "Sri";
name is a variable
"Sri" is a String literal
Stored in heap memory, and referenced by name
9 Why is String special in Java?
String is a Class in [Link] package
It has many built-in methods to work with text
Strings are immutable — once created, they cannot be changed
10 What is a Method in Java?
A method in Java is a block of code that performs a specific task.
It runs only when you call it, and it helps avoid repeating code.
Type Example Notes
Built-in length(), charAt() Already provided by Java
User-defined greet(), addNumbers() You write your own
returnType methodName (parameters)
{
// body of the method
}
EX:
int add (int a, int b)
{
return a + b;
}
11 What is interface ?
An interface in Java is a contract or blueprint that contains only method declarations
(without body).
The class that implements the interface must provide the method definitions.
*************************************************
//CentralTraffic (It is an interface)
public interface CentralTraffic
{
int a=4; //public
public void greenGo();
public void redStop();
public void FlashYellow();
}
//ContinentalTraffic (It is an interface)
public interface ContinentalTraffic
{
public void Trainsymbol();
}
***********CLASS**************** (which implements all methods declared
in interfacec)
public class AustralianTrafic implements CentralTraffic, ContinentalTraffic
{
public void walkonsymbol() //own class method
{
[Link]("walking");
}
@Override
public void redStop() {
[Link](" redstop implementation");
}
@Override
public void FlashYellow() {
[Link](" flash yellow implementation");
//code
}
@Override
public void greenGo() {
[Link](" Green go implementation");
}
@Override
public void Trainsymbol() {
public static void main(String[] args)
{
CentralTraffic a = new AustralianTrafic();
[Link]();
[Link]();
[Link]();
AustralianTrafic at=new AustralianTrafic();
ContinentalTraffic ct=new AustralianTrafic();
[Link]();
[Link]();
}
12 What is Abstraction in Java?
Abstraction means hiding internal details and showing only the necessary features to
the user.
💡 Like a car: You press the brake, but you don’t need to know how it works inside.
✅ What is an Abstract Class?
An abstract class is a class that cannot be instantiated, and it can have both abstract
and non-abstract methods.
abstract classes cannot be instantiated”, it means:
🔸 You cannot create an object directly from that class using new
public abstract class Animal
{
public abstract void makeSound(); // abstract method
Public void eat() //non abstract method
{
}
}
public class Dog extends Animal
{
public void makeSound()
{
[Link]("Dog barks!");
}
}
public class Main {
public static void main(String[] args) { Dog a = newDog();
Animal a = new Dog(); // ✅ Allowed - object of subclass
[Link](); // Output: Dog barks!
}
}
13 What is Inheritance in Java?
Inheritance means one class (child) can inherit properties and methods from another
class (parent).
🔶 Why use Inheritance?
Code Reusability → write once, use in many classes.
extends keyword is used.
Parent = Superclass
Child = Subclass
* Multiple inheritance is not allowed here in java. So it is achieved through
interface.
14 What is Function Overloading? / / *COMPILE TIME POLYMORPHISM*
Function Overloading means multiple methods in the same class with the same name
but different parameters.
Why use it?
To perform different tasks using the same method name with different inputs.
public class Calculator {
// First method
public void add(int a, int b) {
[Link]("Sum is: " + (a + b));
}
// Second method (Overloaded)
public void add(double a, double b) {
[Link]("Sum is: " + (a + b));
}
// Third method (Overloaded)
public void add(int a, int b, int c) {
[Link]("Sum is: " + (a + b + c));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link](2, 3); // Output: 5
[Link](2.5, 3.5); // Output: 6.0
[Link](1, 2, 3); // Output: 6
}
}
Happens at compile time — so it's called Compile Time Polymorphism.
15 What is Function Overriding?
Function Overriding means writing a method in the child class with the same name,
return type, and parameters as in the parent class.
🔶 Why use it?
To change or customize the behavior of a method inherited from the parent class.
public class Animal {
public void makeSound() {
[Link]("Animal makes a sound");
public class Dog extends Animal {
@Override
public void makeSound() {
[Link]("Dog barks");
}
public static void main(String[] args) {
Dog dog = new Dog();
[Link](); // Output: Dog barks
Key Points:
Must be in inheritance (parent-child).
Method name, return type, and arguments must be exactly same.
Happens at runtime — called Runtime Polymorphism.
Use @Override annotation to make it clear.
16 What is constructor ?
Whenever we create an object for the class, the constructor will be called and the
block of code gets executed.
Its name is the same as the class name.
It has no return type (not even void).
When no constructor is defined in the class, java by default will call the default
constructor.
Types : Default / Parameterized constructor
17 About - SUPER KEYWORD in java
super keyword in Java is used to refer to the immediate parent class.
It is very useful when you're working with inheritance.
Uses of super:
Access parent class constructor - super(); - keyword used in child class
constructor as first line only
Access parent class methods
Access parent class variables
18 THIS - KEYWORD :
this keyword refers to the current class object / variables.
int a =2;
public void m1()
{
int a = 3;
int b = a+this.a;
[Link](b);
}
public static void main(String[] args) {
Main obj = new Main();
obj.m1();
19 STATIC - keyword / STATIC variables.
Static variables are the variables that depends upon the class, which are known as
the class variables.
Whereas - Instance varibles are variables that depends upon the objects. But static
varibles doesnot depends upon the objects.
Variables that are initialized inside the constructor are known as - local variables
When a method is marked as STATIC - It means that the method doesnt rely on the
object to get called. It gets called with the class name.
So static methods / variables - does not rely on the objects.
20 What is final in Java?
The final keyword is used to restrict the user. It can be applied to:
Variables
Methods
Classes
21 What are Access Modifiers in Java?
Access modifiers are keywords that decide the visibility (access level) of classes,
methods, variables, and constructors.
Modifier Access Level
public Accessible from anywhere (any class, package)
private Accessible only within the same class
Protected Accessible in same package + subclasses (child classes)
(no modifier) Also called default – accessible only in same package
22 what is exception handling ?
Exception handling is - Handling an unexpected event that has occurred during
execution of the program
Dividing by zero
Accessing an invalid array index
Trying to open a file that doesn't exist
Common Exception Types:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
FileNotFoundException
IOException
public class Main {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // This will cause ArithmeticException
[Link](c);
catch (ArithmeticException e)
[Link]("Cannot divide by zero!");
}
finally {
[Link](" This will always run. Even if the code failed somewhere
in the middle ");86
23 What is collections in java ?
Collection in Java is a framework that provides classes and interfaces to store
and manipulate groups of data. It includes List, Set, Map etc., and helps perform
operations like adding, removing, sorting data efficiently.
Why Collections?
Without Collections, we use arrays — which:
Have fixed size
Can hold only same type of data
Collections solve these problems.
Popular Classes in Collection:
Interface Class Example Use
List ArrayList List of students in a class
List LinkedList Playlist of songs
Set HashSet Unique student IDs
Map HashMap Roll number ↔ Name
24 What is an ArrayList in Java?
An ArrayList is a resizable array in Java.
It is a part of Java's Collection Framework under the package [Link].
✅ Key Points:
Unlike arrays, you don’t need to define a fixed size.
It grows automatically when elements are added.
It can store duplicate values.
import [Link];
public class Exercise {
public static void main (String args[]) {
List<String> a = new ArrayList<String>(); // LIST - interface
[Link]("apple"); // ArrayList - class
[Link]("banana");
[Link]("cherry");
[Link]("mango");
[Link]("apple");
[Link](a);
[Link](0);
[Link](a);
[Link]([Link]("orange"));
boolean statement = [Link]("orange");
if(statement = = true)
[Link]("Orange is found");
}
else
[Link]("Orange is not found");
[Link]([Link]());
for(String str : a)
[Link](str);
for(int i=0; i<[Link]();i++)
[Link]("Index " + i + ": " + [Link](i));
Some Common Methods:
add() Adds an element
remove() Removes by index or value
get(index) Gets the element at the index
set(index, value) Replaces the element
contains(value) Checks if element is present
size() Returns number of elements
clear() Removes all elements
25 What is set / HASHSET ?
A HashSet is a collection used to store unique elements only — no duplicates
allowed.
It is part of the Java Collections Framework and is based on a hash table.
When to Use?
Use HashSet when:
You want no duplicates.
You don’t care about order.
Set<String> fruits = new HashSet<String>();
[Link]("apple");
[Link]("banana");
[Link]("mango");
for (String fruit : fruits)
[Link](fruit);
ITERATOR
HashSet<String> fruits = new HashSet<>();
[Link]("apple");
[Link]("banana");
[Link]("mango");
Iterator<String> it = [Link]();
while ([Link]())
[Link]([Link]());
26 What is a HashMap in Java?
A HashMap is part of Java’s Collection Framework. It is used to store data in key-
value pairs.
HashMap<String, String> map = new HashMap<>();
// adding key-value pairs
[Link]("apple", "red");
[Link]("banana", "yellow");
[Link]("grape", "purple");
// printing the map
[Link](map);
for (String key : [Link]())
{
[Link]("Key: " + key + ", Value: " + [Link](key));
27 What is the differnece between HASHMAP AND HASHTABLE
Hashmap is not thread safe - ie, It is not synchronized
It allows one null value
We can loop through the hasmap by using - iterator
But Hashtable is thread safe - ie, It is synchronized.
It allows no null values in the table.
But here we cannot use iterator - we have to use enumerator.
************************ *************** *******************
28 OOPS Interview questions - source - Rahul shetty
************************ *************** *******************
1 What are the core concepts of OOPS?
OOPS core concepts are;
Abstraction
Encapsulation
Polymorphism
Inheritance
Composition
Association
Aggregation
2 What is Abstraction?
Abstraction means hiding the internal details and showing only the essential features
to the user.
Abstraction is achieved using:
Abstract Classes
Interfaces
3 What is Encapsulation?
Encapsulation is the process of wrapping data (variables) and code (methods) together
in a single unit - usually a class.
It helps to protect data from being accessed directly and gives controlled access
through methods.
4 What is the difference between Abstraction and Encapsulation?
“Program to interfaces, not implementations” is the principle for Abstraction and
“Encapsulate what varies” is the OO principle for Encapsulation.
Abstraction provides a general structure of a class and leaves the details for the
implementers. Encapsulation is to create and define the permissions and restrictions of
an object and its member variables and methods.
Abstraction is implemented in Java using interface and abstract class while
Encapsulation is implemented using four types of access level modifiers: public,
protected, no modifier and private.
5 What is Polymorphism?
What is Polymorphism?
Polymorphism means "many forms".
In Java, one thing behaves in different ways based on how you use it.
6 What is Inheritance?
A subclass can inherit the states and behaviors of it’s super class is known as
inheritance.
7 What is multiple inheritance?
A child class inheriting properties and behaviors from multiple parent classes is
known as multiple inheritance.
8 What is the diamond problem in inheritance?
In case of multiple inheritance, suppose class A has two subclasses B and C, and a
class D has two super classes B and [Link] a method present in A is overridden by both
B and C but not by D then from which class D will inherit that method B or C? This
problem is known as diamond problem.
/ \
B C
\ /
9 Why Java does not support multiple inheritance?
Java was designed to be a simple language and multiple inheritance introduces
complexities like diamond problem. Inheriting states or behaviors from two different
type of classes is a case which in reality very rare and it can be achieved easily
through an object association.
class A {
void display() { [Link]("From A"); }
class B extends A {
void display() { [Link]("From B"); }
class C extends A {
void display() { [Link]("From C"); }
// ❌ What if:
class D extends B, C {
// Which display() should D use? From B or C?
10 What is Static Binding and Dynamic Binding?
Binding refers to the link between a method call and its actual method body.
Static Binding (Early Binding)
Dynamic Binding (Late Binding)
Static or early binding is resolved at compile time. Method overloading is an example
of static binding.
Dynamic or late or virtual binding is resolved at run time. Method overriding is an
example of dynamic binding.
11 What is a Class?
A class in java is a blueprint - which defines how an object should be . and it
defines variables and methods that how it should be too.
12 What is an Object?
An Object is a instance of class. So when ever an object is being created it means that
it is created in a class.
You can create many objects from a class, and each can have different values.
************************ *************** *******************
29 Java interview questions - source - Rahul shetty
************************ *************** *******************
1 What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a
super class. The
2 What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and
data into a single unit.
3 What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
4 Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
5 Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final
method.
6 Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
7 What is interface?
Interface is a blueprint of a class that have static constants and abstract [Link] can
be used to achieve fully abstraction and multiple inheritance.
8 Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract
keywords can't be used together.
9 Can an Interface be final?
No, because its implementation is provided by another class.
10 What is difference between abstract class and interface?
What is difference between abstract class and interface?
Abstract class Interface
1)An abstract class can have method body (non-abstract methods). Interface have only abstract methods.
2)An abstract class can have instance variables. An interface cannot have instance variables.
3)An abstract class can have constructor. Interface cannot have constructor.
4)An abstract class can have static methods. Interface cannot have static methods.
5)You can extends one abstract class. You can implement multiple interfaces.
11 What is marker interface?
An interface that have no data member and method is known as a marker interface.
For example Serializable, Cloneable etc.
12 Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public. Because they has to be implemented in a class
13 When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements
the referenced interface.
************************ *************** *******************
30 JAVA _ SK DOCUMENT S1
************************ *************** *******************
1Explain constructor chaining with examples from your project / Selenium
WebDriver?
Calling one constructor from another using this() or super() keyword
Example from Selenium Framework (Test Automation)
Suppose you have a BaseTest class that sets up the driver, and a LoginTest class that
extends it:
// [Link]
public class BaseTest {
WebDriver driver;
public BaseTest() {
[Link]("BaseTest Constructor: Launching browser");
// driver = new ChromeDriver(); // Normally you initialize here
// [Link]
public class LoginTest extends BaseTest {
public LoginTest() {
super(); // Calls BaseTest constructor
[Link]("LoginTest Constructor: Navigating to login page");
public void loginToApp() {
[Link]("Login steps executing");
}
public static void main(String[] args) {
LoginTest lt = new LoginTest(); // This triggers constructor chaining
[Link]();
2 Can we have implementation methods in an Interface? If yes, explain with
example
Yes, Java 8 and later allows implementation inside interfaces using:
Default methods
Static methods
3 Difference between final, finally, finalize?
final – Keyword
Used to declare constants, or to prevent modification.
✅ Usage:
final variable – value can’t be changed
final method – method can’t be overridden
final class – class can’t be extended
finally – Block
Used in exception handling.
The finally block always executes, even if an exception occurs or return is used in
try/catch.
4 Can we overload and override main method? if yes / no, explain the reasons
Yes, we can overload the main() method — just like any other method — by
changing the number or type of parameters.
But remember:
👉 Only the standard main(String[] args) is used as the entry point by the JVM.
public class TestMain {
public static void main(String[] args) {
[Link]("Main method with String[]");
main("Sri"); // calling overloaded method
}
public static void main(String name) {
[Link]("Overloaded main: Hello " + name);
}
}
Can we Override the main() method?
No, we cannot override main() in the traditional sense — because:
The main() method is static
Static methods cannot be overridden (they belong to the class, not to instances)
However, you can hide a static method in the subclass — but it’s not true overriding.
5 Can we create an object of an abstract class in Java?
No, we cannot create an object of an abstract class directly.
🧠 Why not?
An abstract class is incomplete — it can have abstract methods (methods with no
body).
So Java doesn’t allow creating an object of it directly, because those methods have no
implementation yet.
✅ But we can create object through a child class
We can extend the abstract class using a concrete (normal) class, and then create an
object of that subclass. That’s how we use abstract classes in real code.
6 What are the differences between StringBuilder and StringBuffer class?
Both StringBuilder and StringBuffer are used to:
Create mutable (changeable) strings
Perform operations like append, insert, delete, reverse, etc.
7 Why String is immutable in Java?
String is immutable for security, performance, thread safety, and memory efficiency.
Why is String immutable in Java?
String is immutable in Java, meaning once created, it cannot be changed.
"String is immutable for security, performance, thread safety, and memory
efficiency.
Reasons Why String is Immutable:
1. Security
Strings are used in sensitive places like:
URL, database credentials, file paths, etc.
If Strings were mutable, someone could modify them after creation, causing security
risks.
Example:
Connection con = [Link]("jdbc:mysql://localhost", "root",
"pass");
If "jdbc:mysql://localhost" could be modified, it would be a huge risk.
2. String Pool (Memory Optimization)
Java stores all string literals in a special String Pool.
Since Strings are immutable, the same string can be shared between multiple
references, saving memory.
Example:
String a = "Sri";
String b = "Sri";
[Link](a == b); // true — points to same object in pool
String is immutable for security, performance, thread safety, and memory
efficiency.
8 Difference between LIST SET MAP
List (Ordered, allows duplicates)
Stores elements in insertion order
Allows duplicates
Can access elements by index
Set (No duplicates, unordered)
Stores unique elements only
No duplicate values
Does not maintain insertion order (unless using LinkedHashSet)
Map (Key-value pairs)
Stores key-value pairs
Keys must be unique
Values can be duplicated
In Selenium:
List<WebElement> is used for dropdowns, checkboxes, or table rows
Set<String> is used in window handling
Map<String, String> is often used in data-driven testing
9 Explain any 3 features from Java 8?
Lambda Expressions
Introduced functional-style programming.
Helps write short, clean, and readable code — especially for iteration or event
handling.
[Link](name - > [Link](name));
Streams API
Can filter, map, sort, collect, count, etc.
[Link]().filter(n -> [Link]("M")).forEach([Link]::println);
Default Methods in Interfaces
Java 8 allows methods with implementation inside interfaces using default keyword.
interface MyInterface {
default void show() {
[Link]("Default implementation");
10 What is the difference between = = and .equals() in Java? How does this
affect string comparison in test automation?
= = compares memory, while .equals() compares the actual value.
In test automation, we should always use .equals() when comparing strings."
In Selenium or test scripts, you compare strings like:
String actual = "Login Successful";
String expected = "Login Successful";
If you do:
if(actual = = expected) // ❌ wrong (compares memory)
It might fail, even though the text is same.
✅ Correct way:
if([Link](expected)) // ✅ right (compares content)
✅ One-line interview answer:
= = compares memory, while .equals() compares the actual value.
In test automation, we should always use .equals() when comparing strings.
************************ *************** *******************
31 TOP 20 JAVA - TESTLEAF - - SK PDF
************************ *************** *******************
11 Can you override static methods in Java?
Answer:
❌ No, we cannot override static methods in Java.
Static methods belong to the class and not to the objects, so method overriding (which
works through objects and dynamic dispatch) doesn't apply to them.
12 What is Serialization?
Serialization means saving a Java object to a file so we can use it later.
✅ What is Deserialization?
Deserialization means loading that object back from the file.
✅ Why is it useful for QA/Testers?
In testing, if we create a test user object once, we can save it (serialize), and then load
it (deserialize) in other test cases — no need to recreate it again and again.
13 In your projects, have you encountered situations where multiple catch
blocks were used without a try block, and if so, could you describe the specific
Scenarios and how you addressed them in terms of error handling or exception
management?
"In Java, we cannot use catch blocks without a try block. A catch must always follow
a try.
But yes, in my project, I have used multiple catch blocks after a single try to handle
different types of exceptions separately."
try {
[Link]("[Link]
WebElement btn = [Link]([Link]("submitBtn"));
[Link]();
catch (NoSuchElementException e) {
[Link]("Element not found: " + [Link]());
catch (TimeoutException e) {
[Link]("Page took too long to load.");
catch (Exception e) {
[Link]("Something went wrong: " + [Link]());
Nested try blocks (try inside try)
Sequential multiple try-catch blocks
14 How do you utilize the ‘super’ keyword in Java to enhance the functionality
or solve specific challenges in your automation testing projects, especially when
working with Selenium, Java, and TestNG frameworks?
15 How does Java manage garbage collection to efficiently handle memory and
prevent memory leaks in your programming projects?
Explanation: Garbage collection in Java automates the process of identifying and
removing unused objects, optimizing memory usage in the Java Virtual Machine
(JVM) during program execution. It prevents memory leaks by reclaiming space
occupied by objects that are no longer needed
16 How have you practically employed list sorting techniques in Java to
efficiently organize and manage data in your development projects?
public class ListSortingExample {
public static void main(String[] args) {
// Example list of product prices
List<Double> productPrices = new ArrayList<Double>();
[Link](19.99);
[Link](29.99);
[Link](14.99);
[Link](39.99);
[Link](productPrices);
// Printing the sorted list
[Link]("Sorted Product Prices (Ascending): " + productPrices);
// Sorting the list in descending order
[Link]([Link]());
// Printing the sorted list in descending order
[Link]("Sorted Product Prices (Descending): " + productPrices);
17 What is the purpose of the Object class in Java?
The Object class provides common methods that all Java objects can use — like:
toString() Gives string representation of an object
equals(Object o) Compares two objects