✅ 1. What is a Constructor?
A constructor is a special block of code that is called automatically when an object is created using the new
keyword.
It is used to initialize object variables (non-static) when the object is born.
✅ 2. Why Do We Use Constructors?
Purpose Explanation
🟢 Initialize variables Assign default or user-given values to object variables
🟢 Save time You don’t need to write extra methods to initialize
🟢 Automate setup Constructor runs automatically when object is created
✅ 3. When is a Constructor Called?
🔸 Every time you create an object using new, the constructor is called.
java
CopyEdit
Student s1 = new Student(); // Constructor runs here automatically
You don’t need to call it manually.
✅ 4. How to Write a Constructor?
🔹 Rules:
Constructor name must be same as class name
It has no return type, not even void
It runs automatically on object creation
🔹 Syntax:
java
CopyEdit
class ClassName {
ClassName() {
// Constructor body
}
✅ 5. Types of Constructor in Java
Type Description
1️⃣ Default Constructor No parameters, used to assign default values
2️⃣ Parameterized Constructor Accepts parameters to set specific values
3️⃣ Copy Constructor (Manual) Copies data from one object to another
🔸 Default Constructor Example:
java
CopyEdit
class Student {
Student() {
System.out.println("Default constructor called");
🔸 Parameterized Constructor Example:
java
CopyEdit
class Student {
String name;
Student(String n) {
name = n;
🔸 Copy Constructor Example:
java
CopyEdit
class Student {
String name;
Student(String n) {
name = n;
Student(Student s) {
name = s.name;
✅ 6. Constructor Overloading
Having multiple constructors in a class with different parameter lists.
java
CopyEdit
class Student {
Student() {
System.out.println("Default");
Student(String name) {
System.out.println("Name: " + name);
Student(String name, int age) {
System.out.println(name + " is " + age + " years old.");
}
✅ 7. this() and super() in Constructors
Keyword Meaning
this() Calls another constructor in the same class
super() Calls constructor of the parent class
java
CopyEdit
class A {
A() {
System.out.println("Parent constructor");
class B extends A {
B() {
super(); // calls A()
System.out.println("Child constructor");
✅ 8. Constructor in Inheritance
The parent class constructor is always called before the child class constructor.
If not written, Java adds super() by default.
✅ 9. Private Constructor
A constructor that is private cannot be accessed from outside the class.
✅ Used in Singleton Pattern (only one object allowed)
java
CopyEdit
class Singleton {
private Singleton() {
// Can't be accessed outside
✅ 10. Constructor vs Method
Feature Constructor Method
Purpose Object initialization Business logic
Called Automatically ✅ Yes ❌ No
Return Type ❌ No return type ✅ Must have
Name Same as class Any name
Can be Inherited ❌ No ✅ Yes
Overloaded? ✅ Yes ✅ Yes
✅ 11. Real-Life Analogy
📱 Imagine ordering a new mobile phone:
Constructor = Setup process (language, brightness, Wi-Fi)
Every time a new phone (object) is made, it runs the same setup (constructor)
✅ 12. Important Interview Questions
Question Sample Answer
What is a constructor? A block that runs automatically when an object is created.
Used to initialize values.
Can we overload constructors? Yes. Constructor overloading is allowed.
Can a constructor be private? Yes, used in Singleton design pattern.
Difference between method and Constructor has no return type, runs automatically. Method
constructor? has return type, runs manually.
Can a constructor be inherited? No, but super() can call parent constructor.
✅ 13. Program Example: All Types
java
CopyEdit
class Employee {
String name;
int age;
// Default Constructor
Employee() {
name = "Not Assigned";
age = 0;
// Parameterized Constructor
Employee(String n, int a) {
name = n;
age = a;
}
// Copy Constructor
Employee(Employee e) {
name = e.name;
age = e.age;
void show() {
System.out.println(name + " - " + age);
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee("Abinaya", 25);
Employee e3 = new Employee(e2); // Copy constructor
e1.show(); // Not Assigned - 0
e2.show(); // Abinaya - 25
e3.show(); // Abinaya - 25
🎯 Final Summary
Topic Mastered?
✅ What & Why ✔️
✅ Types (3) ✔️
✅ Overloading ✔️
✅ this() & super() ✔️
✅ Inheritance & constructor chain ✔️
✅ Private constructor ✔️
✅ Method vs Constructor ✔️
✅ Interview Qs & Programs ✔️
1. What is a constructor in Java?
Answer:
A constructor is a special block in Java that runs automatically when an object is created using the new
keyword. It is used to initialize object (non-static) variables.
🔸 2. How is a constructor different from a method?
Feature Constructor Method
Purpose Initializes object Defines behavior
Return type None Has return type
Called by Automatically Manually
Name Same as class Any name
🔸 3. What are the types of constructors in Java?
Answer:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor (manual in Java)
🔸 4. What is a default constructor?
Answer:
A constructor with no parameters. If you don't define any constructor, Java provides a
default one.
🔸 5. What is a parameterized constructor?
Answer:
A constructor that takes arguments to initialize object variables with user-defined values.
🔸 6. What is constructor overloading?
Answer:
Creating multiple constructors in the same class with different parameter types or counts.
🔸 7. Can a constructor be overloaded?
Answer:
Yes, constructors can be overloaded using different parameter lists.
🔸 8. Can a constructor be private?
Answer:
Yes, a constructor can be private. It is used in the Singleton Design Pattern to restrict object
creation from outside the class.
🔸 9. Can a constructor be static?
Answer:
❌ No. Constructors are called on objects, while static means class-level. So it doesn’t make
sense.
🔸 10. Can a constructor return a value?
Answer:
❌ No. Constructors do not have any return type, not even void.
🔸 11. What is a copy constructor in Java?
Answer:
A constructor that creates a new object by copying data from an existing object. Java
doesn’t have built-in copy constructors, but you can define one manually.
🔸 12. Can we use this() inside a constructor?
Answer:
✅ Yes. this() is used to call another constructor in the same class.
🔸 13. What is super() in constructors?
Answer:
super() is used in a child class constructor to call the parent class constructor. It must be
the first line in the constructor.
🔸 14. What happens if we don’t define any constructor?
Answer:
Java will automatically provide a default constructor.
🔸 15. Can a constructor call a method?
Answer:
✅ Yes, constructors can call methods just like any other block of code.
🔸 16. Can we create object without calling constructor?
Answer:
❌ No. Constructor is always called automatically when the object is created.
🔸 17. Can constructor be inherited?
Answer:
❌ No. Constructors are not inherited, but you can call the parent constructor using super().
🔸 18. What happens if both parent and child have constructors?
Answer:
When child object is created, first parent constructor runs, then child’s constructor.
🔸 19. Difference between constructor and method overloading?
Answer:
Both allow multiple definitions with different parameters, but:
Constructor overloading initializes objects.
Method overloading defines different behaviors.
🔸 20. Can we write logic inside constructor?
Answer:
✅ Yes, but only initialization logic. Don’t write heavy logic like loops or file handling in
constructors.
Q1. What is method overloading?
Answer:
Defining multiple methods with the same name in the same class but with different
parameter lists (type, number, or order).
🔸 Q2. Can method overloading occur within the same class?
Answer:
✅ Yes. Method overloading happens within the same class only.
🔸 Q3. Can we overload methods based on return type only?
Answer:
❌ No. Overloading cannot be done based only on return type. Parameters must differ.
🔸 Q4. Can we overload static methods?
Answer:
✅ Yes. Static methods can be overloaded, but not overridden.
🔸 Q5. Is method overloading a compile-time or runtime concept?
Answer:
✅ Compile-time polymorphism. Java decides which method to call at compile time.
🔸 Q6. What is the benefit of method overloading?
Answer:
It provides flexibility to use the same method name with different types/amounts of data.
🔸 Q7. Can constructors be overloaded?
Answer:
✅ Yes. This is called constructor overloading.
✅ 2. Method Overriding – Interview Questions
🔸 Q8. What is method overriding?
Answer:
When a child class provides its own version of a method that already exists in the parent
class using the same method signature.
🔸 Q9. What are the rules for method overriding?
Answer:
Must be in inheritance (parent-child relationship)
Method signature must be exact same
Access modifier must be same or more visible
Cannot override final, static, or private methods
🔸 Q10. Can we override static methods?
Answer:
❌ No. Static methods belong to the class, not the object. So they can’t be overridden.
🔸 Q11. Can we override private methods?
Answer:
❌ No. Private methods are not inherited, so they cannot be overridden.
🔸 Q12. Can constructors be overridden?
Answer:
❌ No. Constructors are not inherited, so overriding is not possible.
🔸 Q13. What is the use of @Override annotation?
Answer:
To indicate and verify that a method is being overridden.
It helps catch mistakes at compile time.
🔸 Q14. Is method overriding runtime or compile time?
Answer:
✅ Runtime polymorphism — the method to execute is decided at runtime using object
reference.
🔸 Q15. What is dynamic method dispatch?
Answer:
A process where the method call is resolved at runtime using overridden methods based on
the actual object type.
Feature Overloading Overriding
Inheritance Needed? ❌ No ✅ Yes
Class? Same class Parent & Child
Parameters? Must be different Must be same
Return Type? Can vary Usually same
Runtime/Compile-time? Compile-time Runtime
Polymorphism Type Compile-time Runtime
@Override used? ❌ No ✅ Yes
Flexibility Method reusability Method customization
✅ Key Differences: Interview Table
Feature Method Overloading Constructor Overloading
Purpose To perform different tasks To initialize objects in
with same method name different ways
Inheritance needed? ❌ No ❌ No
Return Type Required (void, int, etc.) ❌ Not allowed
Class Name Can be any name Must match class name
Execution Must be called manually Called automatically
during object creation
Example Use print(), add(int a, int b) Student("Abi", 25)
Polymorphism Compile-time Compile-time
Interview Tip Used to handle different Used to create object with
input different setups
✅ Real-Life Example for Both (Your Own Way)
🔸 Method Overloading:
java
CopyEdit
class Calculator {
void add(int a, int b) {
System.out.println(a + b);
void add(double a, double b) {
System.out.println(a + b);
}
Interview Answer:
“I overloaded the add() method for both integers and doubles using different parameters.”
🔸 Constructor Overloading:
java
CopyEdit
class Mobile {
String brand;
int price;
Mobile() {
brand = "Unknown";
price = 0;
Mobile(String b) {
brand = b;
price = 0;
Mobile(String b, int p) {
brand = b;
price = p;
}
Interview Answer:
“I overloaded the Mobile constructor to allow object creation with no values, brand only, or
brand + price.”
“Both allow using the same name with different parameters.
But method overloading is used for behavior (methods), while constructor overloading is
for initializing objects differently.”
✅ Java Polymorphism – Full Interview Q&A
Set
🔶 Basic Concept Questions
1. What is Polymorphism in Java?
Answer:
Polymorphism means "many forms".
In Java, it allows us to perform a single action (like calling a method) in different ways,
depending on the object.
2. What are the types of Polymorphism in Java?
Answer:
Type Also Known As Example
✅ Compile-time Polymorphism Method Overloading add(int, int) / add(double,
double)
✅ Runtime Polymorphism Method Overriding Dog.sound() overrides
Animal.sound()
3. Why do we use Polymorphism?
Answer:
To write flexible, reusable, and clean code
To handle different objects with common interface
To implement OOP concepts like Overriding in Selenium
4. Is constructor overloading a type of polymorphism?
Answer:
Yes. It's considered part of compile-time polymorphism, even though constructors are not
technically methods.
🔶 Compile-Time Polymorphism (Overloading)
5. What is method overloading?
Answer:
Defining multiple methods with the same name but different parameters (type, order, or
number) in the same class.
6. Can we overload methods with different return types?
Answer:
❌ No — return type alone is not enough.
Parameters must be different for overloading to work.
7. Is method overloading polymorphism?
Answer:
✅ Yes, it is compile-time polymorphism.
8. Can we overload static methods?
Answer:
✅ Yes, static methods can be overloaded.
9. Can we overload private methods?
Answer:
✅ Yes. Private methods can be overloaded inside the same class.
🔶 Runtime Polymorphism (Overriding)
10. What is method overriding?
Answer:
When a child class redefines a method from the parent class with the same name,
parameters, and return type.
11. Is method overriding polymorphism?
Answer:
✅ Yes. It is runtime polymorphism.
12. What are the rules of method overriding?
Answer:
Must have same method signature
Must be in inheritance (parent-child)
Access modifier: same or more visible
Return type: same or covariant
Cannot override private, static, or final methods
13. What is dynamic method dispatch?
Answer:
A mechanism by which Java decides at runtime which method to call, based on the object
type, not reference type.
14. Can we override static methods?
Answer:
❌ No. Static methods belong to the class, not the object.
15. Can we override private methods?
Answer:
❌ No. Private methods are not inherited.
16. What is the use of @Override annotation?
Answer:
To inform the compiler that a method is being overridden.
If method signature is wrong, it shows error — helps catch mistakes.
🔶 Polymorphism Real-Time and Advanced Qs
17. How does Java achieve runtime polymorphism?
Answer:
Through method overriding + upcasting:
java
CopyEdit
Animal a = new Dog();
a.sound(); // Dog’s version is called
18. What is upcasting in polymorphism?
Answer:
Referring to a child class object using a parent class reference.
java
CopyEdit
Animal a = new Dog(); // Upcasting
19. Can we achieve polymorphism without inheritance?
Answer:
❌ No. Runtime polymorphism needs inheritance and overriding.
20. Where is polymorphism used in Selenium?
Answer:
WebDriver driver = new ChromeDriver();
WebElement e = driver.findElement();
These show runtime polymorphism — behavior changes based on object type.
✅ Final One-Line Interview Summary
“Polymorphism means one name, many forms. In Java, it allows methods to behave
differently based on input or object type. It is achieved through method overloading
(compile-time) and method overriding (runtime).”
1. What is abstraction in Java?
Answer:
Abstraction is the process of hiding the internal implementation details and showing only
the essential information to the user.
Java achieves abstraction using abstract classes and interfaces.
2. Why is abstraction used?
Answer:
To hide complexity
To improve code maintainability
To provide a clean and understandable interface
To support loose coupling
3. How is abstraction achieved in Java?
Answer:
✅ Using Abstract Classes
✅ Using Interfaces
4. Can we create objects of an abstract class?
Answer:
❌ No. You cannot instantiate an abstract class directly.
But you can use it to define a reference and initialize it with a child object.
5. Can abstract classes have constructors?
Answer:
✅ Yes. Abstract classes can have constructors to initialize common properties, but you
can’t create their objects directly.
6. Can we define a method body in an abstract class?
Answer:
✅ Yes. Abstract class can have both abstract methods (without body) and concrete
methods (with body).
7. Can abstract classes have static methods?
Answer:
✅ Yes. Abstract classes can have static methods.
🔶 Abstract Class vs Interface Questions
8. What is the difference between abstract class and interface?
Feature Abstract Class Interface
Keyword abstract interface
Methods Abstract + Concrete All abstract (Java 7), default +
static (Java 8+)
Variables Any type public static final only
Inheritance Single Multiple
Constructor ✅ Yes ❌ No
Access Modifiers Can be private/protected All members are public
9. When to use abstract class over interface?
Answer:
Use an abstract class when:
You need common variables or methods
You want to provide partial implementation
You want to include constructors
Use an interface when:
You want to force multiple unrelated classes to implement the same behavior
You need multiple inheritance
10. Can abstract class implement interface?
Answer:
✅ Yes. An abstract class can implement one or more interfaces and may or may not provide
method definitions.
11. Can interface extend another interface?
Answer:
✅ Yes. Interfaces can extend multiple other interfaces.
12. Can abstract class extend another abstract class?
Answer:
✅ Yes. Abstract classes can extend other abstract classes.
🔶 Practical & Advanced Interview Questions
13. Can an abstract class have a main() method?
Answer:
✅ Yes. It can have a main() method and can be executed like a regular class, but you still
can’t create an object of it.
14. Can interface methods have a body in Java 8+?
Answer:
✅ Yes. Java 8 introduced default and static methods with body inside interfaces.
15. What happens if a class does not implement all methods of an interface?
Answer:
That class must be declared abstract; otherwise, a compile-time error will occur.
16. Is it mandatory to override all abstract methods in a subclass?
Answer:
✅ Yes, unless the subclass is also declared abstract.
17. Can an interface extend an abstract class?
Answer:
❌ No. An interface can only extend another interface — it cannot extend a class (abstract or
not).
18. Can a class be both abstract and final?
Answer:
❌ No. abstract means it needs to be inherited,
final means it cannot be inherited. So, they conflict.
19. Can an abstract class have private methods?
Answer:
✅ Yes. It can have private, protected, public, and default methods — only abstract methods
must be public or protected.
20. Where is abstraction used in real-time automation projects?
Answer:
In Selenium, we use abstraction to:
Hide browser setup details inside base classes
Implement frameworks like Page Object Model (POM)
Define WebDriver as an interface:
WebDriver driver = new ChromeDriver(); — we don't care about how ChromeDriver is
implemented internally
🧠 One-line Summary for Interview:
“Abstraction means hiding internal details and showing only the essential features.
It helps simplify complex systems and is achieved using abstract classes and interfaces in
Java.”
Encapsulation in Java – Full Interview Q&A
This is a simple but powerful concept — and it's very commonly asked in interviews for QA
testers, automation engineers, and developers.
✅ 1. What is Encapsulation?
Answer:
Encapsulation is the process of wrapping variables (data) and methods (code) together as
a single unit, typically using a class.
It is also called data hiding.
✅ It protects data from unauthorized access
✅ It allows controlled access using getters and setters
🧠 Real-Life Example:
Think of a capsule — it hides bitter medicine inside.
Similarly, Java hides complex internal data inside a class and gives only what is needed.
✅ 2. Why is Encapsulation Important?
Benefit Explanation
Security Data can't be accessed directly
Control You decide how to expose or restrict values
Maintainability Easy to modify and reuse code
Flexibility You can make class changes without affecting
other code
✅ 3. How to Achieve Encapsulation in Java?
4 Steps to achieve full encapsulation:
1. Declare variables private
2. Provide public getters to read data
3. Provide public setters to update data
4. Wrap them inside a class
✅ Example:
java
CopyEdit
class Student {
private String name;
private int age;
// Getter
public String getName() {
return name;
// Setter
public void setName(String name) {
this.name = name;
// Getter
public int getAge() {
return age;
// Setter
public void setAge(int age) {
this.age = age;
🔸 In main():
java
CopyEdit
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Abinaya");
s.setAge(25);
System.out.println("Name: " + s.getName());
System.out.println("Age: " + s.getAge());
✅ 4. Interview Q&A on Encapsulation
🔹 Q1: What is encapsulation in Java?
Answer:
Encapsulation is binding data (variables) and methods into a single unit.
It hides internal data from outside access.
🔹 Q2: How is encapsulation implemented?
Answer:
Make variables private
Use public getters and setters
Keep logic hidden inside the class
🔹 Q3: Why is encapsulation also called data hiding?
Answer:
Because it hides the internal details of an object from outside classes using access
modifiers.
🔹 Q4: What are the benefits of encapsulation?
✅ Better security
✅ Controlled access
✅ Reusability
✅ Maintenance ease
🔹 Q5: Can you access private variables directly?
Answer:
❌ No. Private variables cannot be accessed directly outside the class.
You must use getters/setters.
🔹 Q6: Is encapsulation a part of OOPs?
Answer:
✅ Yes. It’s one of the four pillars of Object-Oriented Programming:
Abstraction
Encapsulation
Inheritance
Polymorphism
🔹 Q7: What happens if you don’t use encapsulation?
Answer:
Anyone can modify your data directly, which can lead to security issues, bugs, and lack of
control.
🔹 Q8: Can a class be fully encapsulated?
Answer:
✅ Yes. If all data members are private and only accessible through public methods
(getters/setters), the class is fully encapsulated.
🧠 How to Say in Interview (Your Own Words):
"Encapsulation means binding data and logic inside a class.
I use private variables and expose them with public getters and setters.
This helps protect the data and control who can access or modify it."
✅ Summary Table
Feature Encapsulation
Meaning Data hiding and wrapping
How private variables + public getters/setters
Why Protect and control access
Real use Forms, banking data, personal info
OOP Pillar Yes, one of the four
✅ 1. What is Inheritance?
Answer:
Inheritance is the process by which one class (child) can acquire properties and behaviors
(variables & methods) of another class (parent).
It helps in code reuse, avoids duplication, and supports runtime polymorphism.
🧠 Real-Life Example:
A child inherits properties from parents (like eyes, skin color).
Similarly, a subclass inherits variables & methods from a superclass.
✅ 2. Types of Inheritance in Java
Type Support in Java? Example
✅ Single ✅ Supported A→B
✅ Multilevel ✅ Supported A→B→C
❌ Multiple ❌ Not directly (use A←B&C ❌
interface)
✅ Hierarchical ✅ Supported A → B, C, D
✅ Hybrid ❌ Not directly (use Mixed
interface)
✅ 3. Basic Example – Single Inheritance
java
CopyEdit
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited from Animal
d.bark(); // own method
✅ 4. Interview Questions on Inheritance
🔹 Q1: What is inheritance in Java?
Answer:
Inheritance is a feature where one class inherits (gets) the fields and methods of another
class using the extends keyword.
🔹 Q2: Why is inheritance used?
Answer:
To reuse code
To avoid duplication
To support polymorphism
To extend existing functionality
🔹 Q3: What is the extends keyword?
Answer:
extends is used to define inheritance between two classes.
java
CopyEdit
class Dog extends Animal {}
🔹 Q4: Does Java support multiple inheritance?
Answer:
❌ No, Java does not support multiple inheritance with classes due to the diamond
problem.
✅ But it supports it through interfaces.
🔹 Q5: What are the different types of inheritance supported in Java?
✅ Single
✅ Multilevel
✅ Hierarchical
❌ Multiple (via class)
✅ Hybrid (via interface)
🔹 Q6: What is multilevel inheritance?
Answer:
Inheritance in three or more levels (e.g., A → B → C)
🔹 Q7: What is hierarchical inheritance?
Answer:
One superclass and multiple subclasses
java
CopyEdit
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
🔹 Q8: What is the problem with multiple inheritance?
Answer:
Java avoids it to prevent ambiguity caused by the diamond problem.
🔹 Q9: How does Java solve multiple inheritance?
Answer:
Java solves it by using interfaces. A class can implement multiple interfaces.
🔹 Q10: What is super keyword?
Answer:
super is used to:
Access parent class methods and variables
Call parent class constructor
java
CopyEdit
super.method();
super.variable;
super(); // to call constructor
✅ 5. Interview Tips (Your Own Words)
“Inheritance helps me write reusable, maintainable code.
In my example, Dog inherits the eat() method from Animal class.
I used extends to set the relationship.
In Selenium too, we use inheritance to share common driver setups.”
✅ Summary Table
Feature Inheritance
Keyword extends
Purpose Code reuse, OOP design
Types Supported Single, Multilevel, Hierarchical
Multiple Inheritance ❌ (via class), ✅ (via interface)
Key Usage Reusability + Runtime polymorphism
Access Modifiers in Java – Full Interview Q&A
✅ 1. What are Access Modifiers?
Answer:
Access Modifiers in Java are keywords used to control the visibility (access level) of
classes, variables, methods, and constructors.
They help in implementing encapsulation and data security.
✅ 2. Types of Access Modifiers
Modifier Access Level Accessible From
public Highest Anywhere (any
package/class)
protected Medium Same package or subclass
default (no keyword) Package-level Same package only
private Lowest Same class only
✅ 3. Real-Life Analogy:
Imagine a building:
public → Main gate (anyone can enter)
protected → Apartment residents + relatives
default → Only residents (same building)
private → Your bedroom (only you)
✅ 4. Code Example (All in One)
java
CopyEdit
public class Person {
public String name = "Abi";
private int age = 25;
protected String city = "Chennai";
String college = "Anna University"; // default
public void showName() {
System.out.println("Name: " + name);
private void showAge() {
System.out.println("Age: " + age);
protected void showCity() {
System.out.println("City: " + city);
void showCollege() {
System.out.println("College: " + college);
✅ 5. Interview Q&A on Access Modifiers
🔹 Q1: What is the use of access modifiers?
Answer:
They are used to restrict or allow access to classes and their members from other classes
or packages.
🔹 Q2: What is the difference between private and public?
private public
Accessible only in same class Accessible anywhere
Best for security Best for shared functions
🔹 Q3: What is default access modifier?
Answer:
If no modifier is mentioned, it is default/package-private.
Accessible only within the same package.
🔹 Q4: What is protected access?
Answer:
Accessible in:
The same package
Subclasses, even if they’re in different packages
🔹 Q5: Which modifier is most restrictive?
Answer:
private — visible only inside the class
🔹 Q6: Can a class be private?
Answer:
❌ No. Top-level classes cannot be private.
Only inner classes can be private.
🔹 Q7: Can we use multiple access modifiers together?
Answer:
❌ No. You can only use one access modifier per class/method/field.
🔹 Q8: Which access modifier is used for maximum security?
Answer:
private — fully hides data from outside access.
🔹 Q9: Can constructors be private?
Answer:
✅ Yes. Used in singleton design pattern to restrict object creation.
🔹 Q10: Can interfaces have access modifiers?
Answer:
Interfaces are public or default
Interface methods are public abstract by default (till Java 7)
✅ Summary Table
Modifier Same Class Same Package Subclass (diff Outside Pkg
pkg)
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌
🧠 How to Explain in Interview (Own Words)
“Access modifiers help me control how much of my class is exposed to others.
I use private for variables and give public getters/setters — that’s how I achieve
encapsulation.
Also, in real-time frameworks, we use protected for base methods like setup() so
subclasses can access them.”
Static vs Non-Static in Java – Full Interview
Q&A
This is one of the most frequently asked topics in Java interviews for freshers and QA
automation testers.
✅ 1. What is the meaning of static in Java?
Answer:
static is a keyword used to create variables or methods that belong to the class itself, not
to any specific object.
✅ Shared across all objects
✅ Loaded once in memory during class loading
✅ 2. Static vs Non-Static – Key Differences
Feature static non-static
Belongs to Class Object
Accessed using Class name (or object) Only object
Memory Loaded once per class Each object has its copy
Use case Common data/method Instance-specific logic
Can access Only other static stuff Both static and non-static
✅ 3. Example: Static vs Non-Static
java
CopyEdit
public class Student {
static String college = "Anna University"; // static variable
String name; // non-static variable
static void showCollege() {
System.out.println("College: " + college);
// System.out.println(name); ❌ ERROR: can't access non-static variable
}
void showName() {
System.out.println("Name: " + name);
System.out.println("College: " + college); // ✅ can access static
}
main() Example:
java
CopyEdit
public class Main {
public static void main(String[] args) {
Student.showCollege(); // calling static method without object
Student s1 = new Student();
s1.name = "Abinaya";
s1.showName(); // calling non-static method with object
✅ 4. Interview Q&A – Static vs Non-Static
🔹 Q1: What is the static keyword?
Answer:
It allows a variable/method to be shared across all instances of a class.
🔹 Q2: Can we call a static method without creating an object?
Answer:
✅ Yes. You can call it using the class name directly.
java
CopyEdit
Math.sqrt(4); // static method
🔹 Q3: Can a static method access non-static variables?
Answer:
❌ No. Static methods cannot access instance variables directly.
🔹 Q4: Can non-static methods access static variables?
Answer:
✅ Yes. Non-static methods can access both static and non-static members.
🔹 Q5: When is a static block executed?
Answer:
A static block is executed once when the class is loaded (before main()).
java
CopyEdit
static {
System.out.println("Static Block");
🔹 Q6: What are static blocks used for?
Answer:
To initialize static data or perform setup logic before the class is used.
🔹 Q7: What is a static variable?
Answer:
A class-level variable shared across all instances.
java
CopyEdit
static int count;
🔹 Q8: Can a class be static?
Answer:
✅ Yes — but only nested classes can be static.
Top-level classes cannot be static.
🔹 Q9: What happens if we change a static variable in one object?
Answer:
The change reflects in all objects because static variables belong to the class, not objects.
🔹 Q10: When to use static?
Answer:
For utility methods (e.g., Math.max())
For constants
For shared counters or configuration values
🧠 How to Explain in Interview (Your Own Words):
“Static means the member belongs to the class.
I use static for shared data like college name and non-static for object-specific data like
student name.
I also use static methods in utility/helper classes.
In testing frameworks, we use static blocks for setup or config loading.”
✅ Summary Table
Concept Static Non-Static
Tied to Class Object
Memory Once per class Per object
Accessed by Class name or object Only object
Example use Utility methods, constants Object behavior, instance
data
1. What is this in Java?
Answer:
this is a reference keyword in Java that refers to the current object of the class.
Think of this as saying: “Me — the current object”
✅ Uses of this:
1. To refer to current class variables
2. To call current class methods
3. To call current class constructors (this())
4. To pass current object as a parameter
5. To return current class object
🔸 Example:
java
CopyEdit
class Student {
String name;
Student(String name) {
this.name = name; // refers to current object’s variable
✅ 2. What is super in Java?
Answer:
super is a keyword used to refer to the parent class (superclass) members.
Think of super as saying: “My parent’s version”
✅ Uses of super:
1. To access parent class variables
2. To call parent class methods
3. To call parent class constructor (super())
🔸 Example:
java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // calls parent method
System.out.println("Dog barks");
✅ 3. this() vs super() – Constructor Calls
Keyword Calls
this() Another constructor in the same class
super() Constructor of the parent class
Position Must be first line in constructor
🔸 Constructor Example:
java
CopyEdit
class Animal {
Animal() {
System.out.println("Animal constructor");
class Dog extends Animal {
Dog() {
super(); // must be first
System.out.println("Dog constructor");
✅ 4. Interview Q&A – this vs super
🔹 Q1: What is this keyword in Java?
Answer:
this refers to the current class object. It's used to differentiate between local and instance
variables.
🔹 Q2: What is super keyword in Java?
Answer:
super refers to the parent class and is used to access its methods, variables, or
constructor.
🔹 Q3: Can this() and super() be used in the same constructor?
Answer:
❌ No. Only one constructor call is allowed, and it must be the first line.
🔹 Q4: When is super() automatically called?
Answer:
If not written explicitly, the Java compiler automatically adds super() in child class
constructors.
🔹 Q5: Can we use this and super in static methods?
Answer:
❌ No. this and super refer to objects — and static methods do not have objects.
🔹 Q6: What is the difference between this.variable and variable?
Answer:
If the method parameter and instance variable have the same name, this.variable refers to
the instance variable.
🔹 Q7: Why do we use super()?
Answer:
To initialize parent class properties before executing child constructor logic.
🔹 Q8: Can we call a parent method without super?
Answer:
✅ Yes, if the parent method is not overridden.
If overridden, then use super.methodName() to call the parent version.
✅ 5. Summary Table – this vs super
Keyword Refers to Used for Can be used in
this Current class Variables, Any non-static
methods, context
constructors
super Parent class Methods, In child class only
variables,
constructors
🧠 How to Answer in Interview (Your Own Words):
“I use this to refer to the current object, especially when local and instance variable names
clash.
I use super when I want to access or call anything from the parent class, like a constructor
or method.”
1. What is final in Java?
Answer:
The final keyword is used to restrict modification.
It can be applied to:
Variables
Methods
Classes
✅ 2. Use Cases of final
Usage Meaning
final variable Value cannot be changed (constant)
final method Method cannot be overridden
final class Class cannot be inherited
🔸 Example 1: Final Variable (Constant)
java
CopyEdit
class Student {
final String college = "Anna University";
void show() {
// college = "XYZ University"; ❌ ERROR: cannot reassign final variable
System.out.println(college);
🔸 Example 2: Final Method
java
CopyEdit
class A {
final void display() {
System.out.println("A class method");
}
class B extends A {
// void display() {} ❌ ERROR: Cannot override final method
}
🔸 Example 3: Final Class
java
CopyEdit
final class Vehicle {
void run() {
System.out.println("Running...");
// class Bike extends Vehicle {} ❌ ERROR: Cannot extend final class
✅ 3. Interview Questions on final
🔹 Q1: What is the use of the final keyword?
Answer:
It is used to restrict changes:
Final variable = constant
Final method = no override
Final class = no subclassing
🔹 Q2: What happens if we try to modify a final variable?
Answer:
❌ Compilation error. Final variables cannot be reassigned once initialized.
🔹 Q3: Can final variables be initialized later?
Answer:
✅ Yes, but only once, either:
During declaration
Inside a constructor
java
CopyEdit
final int id;
Student() {
id = 101; // allowed
🔹 Q4: Can we override a final method?
Answer:
❌ No. Final methods cannot be overridden in a subclass.
🔹 Q5: Can we inherit a final class?
Answer:
❌ No. Final class cannot be extended.
🔹 Q6: Can a constructor be final?
Answer:
❌ No. Constructors cannot be final, because they are not inherited or overridden.
🔹 Q7: Can final variables be static?
Answer:
✅ Yes. They are called constants (static final).
java
CopyEdit
static final double PI = 3.14;
🔹 Q8: What is the difference between final, finally, and finalize()?
Term Meaning
final Keyword to restrict
finally Block in exception handling
finalize() Method called by GC before object
deletion
✅ Summary Table
Keyword Use Restriction
final variable Cannot be modified
final method Cannot be overridden
final class Cannot be extended
🧠 How to Say in Interview (Own Words):
“I use the final keyword to restrict behavior.
If I want a value to remain constant like PI, I declare it as final.
If I don’t want others to override my method, I mark it final.
Also, in automation frameworks, constants like URL, timeouts are often static final.”
. Interview Questions – Exception Handling
🔹 Q1: What is the difference between error and exception?
Exception Error
Recoverable Not recoverable
Handled using try-catch Cannot be handled
Ex: FileNotFound Ex: StackOverflowError
🔹 Q2: What are checked and unchecked exceptions?
Type Occurs Example
Checked Compile-time IOException, SQLException
Unchecked Runtime NullPointerException,
ArrayIndexOutOfBoundsEx
ception
🔹 Q3: What is the difference between throw and throws?
throw throws
Used to throw an exception manually Declares exception in method signature
One exception only Multiple exceptions allowed
Inside method After method name
🔹 Q4: What is finally block?
Answer:
finally block always executes whether exception occurs or not.
Used to close resources like files, DB, WebDriver.
🔹 Q5: Can we have try without catch?
Answer:
✅ Yes, but only if we use finally.
java
CopyEdit
try {
// code
} finally {
// clean-up
🔹 Q6: Can we have multiple catch blocks?
Answer:
✅ Yes. Used to handle multiple types of exceptions.
java
CopyEdit
try {
// code
} catch (ArithmeticException e) {
} catch (NullPointerException e) {
🔹 Q7: What is the purpose of exception handling?
Answer:
To prevent program crash
To handle errors in a graceful way
To maintain flow and stability
🔹 Q8: Can we catch multiple exceptions in a single catch?
Answer:
✅ Yes. Since Java 7:
java
CopyEdit
catch (IOException | SQLException e) {
e.printStackTrace();
✅ 5. Real-Time Example in Selenium
java
CopyEdit
try {
driver.findElement(By.id("login")).click();
} catch (NoSuchElementException e) {
System.out.println("Element not found");
} finally {
driver.quit(); // always close browser
✅ Summary Table
Concept Purpose
try Write risky code
catch Handle specific exception
finally Always run this block
throw Manually raise an exception
throws Inform caller that method might throw
🧠 How to Say in Interview (Your Own Words):
“Exception handling allows me to write secure, stable programs.
I use try-catch to handle errors like divide by zero or null pointer.
In Selenium, I wrap risky actions in try-catch and use finally to quit the driver.”
1. What are Wrapper Classes?
Answer:
Wrapper classes are used to convert primitive data types into objects.
Java is object-oriented. But primitive types (like int, char) are not objects — so Java gives
us wrapper classes.
✅ 2. Why Do We Need Wrapper Classes?
✅ To work with collections (ArrayList, HashMap, etc.) which only store objects
✅ For conversion between strings and numbers
✅ To use utility methods (like parseInt(), compareTo(), etc.)
✅ For autoboxing and unboxing
✅ 3. List of Primitive → Wrapper Class
Primitive Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
✅ 4. Example – Primitive to Wrapper
java
CopyEdit
int a = 10; // primitive
Integer obj = Integer.valueOf(a); // wrapping
➕ Unboxing (Object to Primitive)
java
CopyEdit
int b = obj.intValue(); // unwrapping
✅ 5. Autoboxing and Unboxing
Since Java 5, autoboxing/unboxing automatically converts between primitive and object:
java
CopyEdit
Integer x = 100; // autoboxing
int y = x; // unboxing
✅ 6. Common Methods in Wrapper Classes
Method Purpose
parseInt("123") Converts String to int
toString(123) Converts int to String
compareTo() Compares two objects
valueOf() Converts primitive to object
🔸 Example: parseInt() vs valueOf()
java
CopyEdit
int i = Integer.parseInt("100"); // returns int
Integer j = Integer.valueOf("100"); // returns Integer object
✅ 7. Interview Questions on Wrapper Classes
🔹 Q1: What is a wrapper class?
Answer:
A class that wraps a primitive data type into an object form.
🔹 Q2: Why do we need wrapper classes?
Answer:
To store primitives in collections
For utility methods (parse, compare, etc.)
For autoboxing/unboxing
For object-oriented features
🔹 Q3: What is autoboxing?
Answer:
Automatic conversion of a primitive to wrapper class object.
java
CopyEdit
int a = 5;
Integer b = a; // autoboxing
🔹 Q4: What is unboxing?
Answer:
Automatic conversion of wrapper object to primitive.
java
CopyEdit
Integer b = 5;
int a = b; // unboxing
🔹 Q5: What is the difference between parseInt() and valueOf()?
Method Return Type Use
parseInt() int Converts string to primitive
valueOf() Integer Converts string to wrapper
object
🔹 Q6: Can we use wrapper classes with collections?
Answer:
✅ Yes. Collections like ArrayList, HashMap can store only objects, not primitives — so wrappers are
required.
🔹 Q7: Is wrapper class mutable?
Answer:
❌ No. Wrapper class objects are immutable.
✅ 8. Real-Time Use in Selenium:
In Selenium or TestNG:
java
CopyEdit
List<Integer> pageNumbers = new ArrayList<>();
pageNumbers.add(1); // uses Integer wrapper
🧠 How to Explain in Interview (Your Own Words):
“Wrapper classes help me use primitive values like int and double as objects.
They're useful when working with collections or converting data formats.
I often use methods like Integer.parseInt() or Double.valueOf() in automation scripts.”
. Interview Questions – Type Casting
🔹 Q1: What is type casting?
Answer:
Type casting is converting one data type into another.
Java supports two types: widening (auto) and narrowing (manual).
🔹 Q2: What is the difference between widening and narrowing?
Widening Narrowing
Small → Big Big → Small
Automatic Manual with casting
No data loss May cause data loss
🔹 Q3: Give an example of narrowing casting.
java
CopyEdit
double d = 9.7;
int i = (int) d; // 9
🔹 Q4: Is type casting allowed between all types?
Answer:
✅ Between compatible types like int → float
❌ Not allowed between incompatible types (e.g., int → String directly)
🔹 Q5: How to convert String to int?
java
CopyEdit
String str = "123";
int num = Integer.parseInt(str);
🔹 Q6: What is class type casting?
Answer:
Used in inheritance, converting parent type to child (downcasting):
java
CopyEdit
Animal a = new Dog(); // upcasting — safe
Dog d = (Dog) a; // downcasting — manual
🔹 Q7: Can type casting cause data loss?
Answer:
✅ Yes — especially in narrowing. Example:
java
CopyEdit
int x = 150;
byte b = (byte) x; // May overflow
✅ 7. Real-Time Use in Testing (Selenium Example)
java
CopyEdit
String price = "299";
int finalPrice = Integer.parseInt(price);
Used when reading text from UI (String) and converting it to int/float for calculations.
✅ 8. Summary Table
Cast Type Example Auto? Risk?
Widening int → long ✅ Yes ❌ No
Narrowing double → int ❌ No ✅ Yes
String to int Integer.parseInt() ❌ ✅ If not number
Class Type Animal a = new Dog(); ✅
Upcasting , ✅ Risk of
Downcasting ❌ ClassCastException
🧠 How to Explain in Interview (Your Own Words):
“Type casting allows me to convert values between different data types.
Widening is safe and automatic, while narrowing requires manual casting and may cause data loss.
In real-time testing, I often convert UI strings to integers using parseInt() for validation.”
Java Scanner Class – Master Guide
🔹 With real-world examples, interview Q&A, and common mistakes
🔰 1. What is the Scanner Class?
Scanner is a built-in class in Java used to take input from the user at runtime via keyboard.
📦 It belongs to the java.util package.
🎯 Mostly used for console-based Java programs and practice apps.
✅ 2. Why do we use Scanner?
We use Scanner to:
Accept user input like int, float, String, etc.
Allow dynamic data instead of hardcoding
Build interactive programs like calculators, login forms, etc.
🔧 3. How to Use Scanner – 3 Steps
➤ Step 1: Import
java
CopyEdit
import java.util.Scanner;
➤ Step 2: Create Object
java
CopyEdit
Scanner sc = new Scanner(System.in);
➤ Step 3: Take Input
java
CopyEdit
int age = sc.nextInt(); // integer
String name = sc.next(); // word
String fullName = sc.nextLine(); // full sentence
float salary = sc.nextFloat(); // float
📘 4. Scanner Input Methods
Method Purpose Example
next() Read a single word Abinaya
nextLine() Read a full sentence Abinaya from Chennai
nextInt() Read integer 25
nextFloat() Read float 45.75
nextDouble() Read double 123.456
nextBoolean() Read true/false true
nextLong() Read long 9876543210L
🔍 5. Full Working Example
java
CopyEdit
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your salary: ");
float salary = sc.nextFloat();
System.out.println("\n--- User Details ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: ₹" + salary);
⚠️ 6. Common Mistake – Buffer Issue
java
CopyEdit
int age = sc.nextInt(); // Takes number
String name = sc.nextLine(); // Skipped!
✅ Fix:
java
CopyEdit
sc.nextLine(); // Consume leftover \n
String name = sc.nextLine(); // Now works fine
💼 7. Real-Time Use Case in Testing
java
CopyEdit
Scanner sc = new Scanner(System.in);
System.out.print("Enter expected product name: ");
String expectedName = sc.nextLine();
WebElement product = driver.findElement(By.id("prod"));
if(product.getText().equals(expectedName)) {
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed!");
🤔 8. Interview Questions with Answers
🔹 Q1: What is the Scanner class used for?
To accept dynamic user input during program execution.
🔹 Q2: Which package is Scanner in?
java.util
🔹 Q3: What is the difference between next() and nextLine()?
next() nextLine()
Reads a word Reads full sentence
Stops at space Stops at enter key
🔹 Q4: How to read different data types?
java
CopyEdit
sc.nextInt(); // int
sc.nextFloat(); // float
sc.nextLine(); // string
sc.nextBoolean(); // true/false
🔹 Q5: What happens if you mix nextInt() and nextLine()?
You get skipped input. Fix it using an extra sc.nextLine();
🔹 Q6: Alternatives to Scanner?
Alternative Used For
BufferedReader Faster input for large data
Console Secure input (e.g., passwords)
Scanner Easy & flexible input for general use
🔹 Q7: Can Scanner be used in automation?
✅ Yes, for dynamic inputs in utility scripts, test data setup, menus, and CLI tools.
🧠 How to Answer in Interview (Own Words)
"I use Scanner when I want the user to provide input during execution — like name, age, or test data.
It supports various data types and is easy to use for practice programs, forms, or test input in automation."
✅ Summary Sheet
Feature Description
Class Scanner
Package java.util
Input Source System.in (keyboard)
Common Methods nextInt(), next(), nextLine(), nextFloat()
Issue Use nextLine() carefully after nextInt()
Use in Selenium For dynamic test input or simulation
🔹 Q1: What is the Scanner class used for in Java?
Answer:
The Scanner class is used to take input from the user at runtime through the keyboard, using the standard
input stream (System.in).
🔹 Q2: Which package contains the Scanner class?
Answer:
java.util
🔹 Q3: How do you create a Scanner object?
Answer:
java
CopyEdit
Scanner sc = new Scanner(System.in);
🔹 Q4: List some commonly used methods of the Scanner class.
Method Description
next() Reads one word
nextLine() Reads the whole line
nextInt() Reads an integer
nextFloat() Reads a float value
nextBoolean() Reads true/false
nextDouble() Reads a double value
🔹 Q5: What is the difference between next() and nextLine()?
Answer:
next() nextLine()
Reads only one word Reads the entire line
Stops at space Stops at Enter key
Ex: "Abi" Ex: "Abi Jack from Chennai"
🔹 Q6: What happens if you use nextLine() after nextInt()?
Answer:
It skips the input because nextInt() doesn't consume the newline (\n) character.
You should add an extra sc.nextLine(); to consume the leftover newline.
🔹 Q7: What is System.in?
Answer:
System.in is the standard input stream connected to the keyboard.
It is passed to Scanner to read data from the user.
🔹 Q8: Is Scanner a buffered class?
Answer:
Yes, Scanner internally uses buffering, but it’s not as fast as BufferedReader for reading large amounts of
input.
✅ Intermediate-Level Questions
🔹 Q9: Can Scanner read all data types?
Answer:
✅ Yes. Scanner supports all primitive data types like int, float, double, boolean, long, and String.
🔹 Q10: What are some limitations of Scanner?
Answer:
Slower than BufferedReader for large input
Needs careful handling of newline issues
No method for reading passwords securely (use Console for that)
🔹 Q11: How can we convert String input to integer manually?
java
CopyEdit
String input = sc.next();
int number = Integer.parseInt(input);
🔹 Q12: Can Scanner be reused?
Answer:
✅ Yes, a single Scanner object can read multiple inputs.
But don’t close Scanner(System.in) too early, or it will close the input stream permanently.
🔹 Q13: What happens if you close the Scanner?
Answer:
It closes the input stream, and further input from the keyboard is no longer possible.
🔹 Q14: Can Scanner read input from files?
Answer:
✅ Yes. It can also read from:
java
CopyEdit
Scanner sc = new Scanner(new File("input.txt"));
🔹 Q15: How do you read multiple lines using Scanner?
Answer:
java
CopyEdit
while(sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
✅ Advanced & Practical Questions
🔹 Q16: What’s the difference between Scanner and BufferedReader?
Scanner BufferedReader
Easy to use Requires more setup
Slower Faster
Supports multiple data types Only reads strings
Used for small input Used for large input
🔹 Q17: In Selenium, can we use Scanner for runtime test input?
Answer:
✅ Yes. Scanner is useful when we want:
Dynamic input for test cases (Ex: Product Name, Login ID)
Menu-based test scripts
Manual test data entry before automation is set up
🔹 Q18: Why shouldn’t we close System.in Scanner too early?
Answer:
Once closed, the System.in stream cannot be reopened, and future input will throw IllegalStateException.
🔹 Q19: Can we read characters one by one using Scanner?
Answer:
Not directly. Scanner doesn’t have nextChar().
We can work around it using:
java
CopyEdit
char ch = sc.next().charAt(0);
🔹 Q20: What are some real-time examples where you’ve used Scanner?
Sample Answer:
"I’ve used Scanner in Java programs for user registration, input validation, and small utilities like calculators
and test data setups.
In testing, I used it to simulate user-provided test inputs dynamically."
🏁 Summary: Key Scanner Interview Highlights
Concept Must Remember
Package java.util
Input source System.in
Common issue nextLine() after nextInt()
Avoid Closing Scanner too early
Use in QA Dynamic input, test cases, console tools
Would you like:
📄 A PDF with all these questions and answers?
✅ A practice set to test your Scanner knowledge?
➡️ Move to the next topic: String vs StringBuffer vs StringBuilder?
Let me know, and we’ll keep up this strong Java learning momentum! 🚀👩💻
You said:
wherscanner read
ChatGPT said:
Great question, Abinaya! 👏
Let’s answer your query clearly and step by step:
❓ Where does Scanner read input from in Java?
✅ Scanner reads input from the input stream you provide when you create it.
💡 Most common input stream:
java
CopyEdit
Scanner sc = new Scanner(System.in);
Here:
System.in is the standard input stream
It points to the keyboard (user typing in console)
➡️ So, in this case, Scanner reads from the keyboard.
✅ Other Input Sources (Not just keyboard)
Scanner can also read input from:
Source Example
Keyboard (console) Scanner sc = new Scanner(System.in);
File Scanner sc = new Scanner(new File("input.txt"));
String Scanner sc = new Scanner("Hello 123 true");
InputStream (like socket or byte stream) Scanner sc = new Scanner(myInputStream);
🔍 Example – Reading from a String:
java
CopyEdit
Scanner sc = new Scanner("Abinaya 25 15000.50");
String name = sc.next();
int age = sc.nextInt();
double salary = sc.nextDouble();
System.out.println(name + ", " + age + ", ₹" + salary);
✅ Output:
CopyEdit
Abinaya, 25, ₹15000.5
🔍 Example – Reading from a File:
java
CopyEdit
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws Exception {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
✅ Summary
Source Scanner Reads From
System.in Keyboard input
File File content
String String tokens
InputStream Any byte stream
If you're preparing for interviews, this is a great point to mention when asked:
“Scanner is a flexible input reader in Java. It can read from keyboard, file, string, or input streams based on
what source we pass to its constructor.
1. What is an Array?
An array is a fixed-size collection of elements of the same data type, stored in contiguous memory.
java
CopyEdit
int[] numbers = {10, 20, 30, 40};
🔹 Fixed size (decided at creation)
🔹 Stores primitive types and objects
🔹 Fast but not flexible
✅ 2. What is an ArrayList?
ArrayList is a class in Java (from java.util package) that acts like a resizable array.
java
CopyEdit
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Abi");
names.add("Jack");
🔸 Dynamic size (grows/shrinks)
🔸 Can store only objects, not primitives (int → Integer)
🔸 Slower than arrays but more flexible
✅ 3. Difference: Array vs ArrayList
Feature Array ArrayList
Size Fixed Dynamic (auto-resize)
Type Can store primitives Stores only objects
Syntax int[] arr = new int[5]; ArrayList<Integer> list = new
ArrayList<>();
Performance Faster Slightly slower (due to resizing)
Inbuilt methods ❌ Very few ✅ Many (add, remove, get,
etc.)
Memory Less flexible Flexible
Import needed? ❌ No ✅ Yes (java.util)
✅ 4. Array Example
java
CopyEdit
int[] marks = new int[3];
marks[0] = 95;
marks[1] = 85;
marks[2] = 75;
System.out.println(marks[1]); // Output: 85
✅ 5. ArrayList Example
java
CopyEdit
import java.util.ArrayList;
ArrayList<String> students = new ArrayList<>();
students.add("Abinaya");
students.add("Divya");
students.add("Keerthi");
System.out.println(students.get(1)); // Output: Divya
✅ 6. Real-Time Use in Automation
Scenario Use
✅ Test data from Excel/DB Store in ArrayList
✅ Fixed config settings Use Array
✅ Iterating and storing test results Use ArrayList
✅ Looping through page elements Use both (if WebElement[])
✅ 7. Interview Questions – Array vs ArrayList
🔹 Q1: What is the main difference between Array and ArrayList?
Answer:
Array is fixed in size; ArrayList is dynamic (can grow or shrink).
🔹 Q2: Can ArrayList store primitive data types?
Answer:
❌ No. It stores only objects, not primitives.
✅ Use Wrapper classes like Integer, Double, etc.
java
CopyEdit
ArrayList<Integer> list = new ArrayList<>();
🔹 Q3: Which is faster – Array or ArrayList?
Answer:
✅ Array is faster because it’s simple and has no overhead of resizing.
❌ ArrayList is slightly slower but more powerful.
🔹 Q4: When to use Array and when to use ArrayList?
Use Case Choose
Known/fixed number of values Array
Dynamic and growing data ArrayList
Need more built-in functions ArrayList
🔹 Q5: How to convert an Array to ArrayList?
java
CopyEdit
String[] arr = {"A", "B", "C"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr));
🔹 Q6: How to convert an ArrayList to Array?
java
CopyEdit
ArrayList<String> list = new ArrayList<>();
list.add("Abi");
String[] arr = list.toArray(new String[0]);
✅ 8. Summary Table (Quick Recap)
Feature Array ArrayList
Size Fixed Growable
Type Any (primitive + object) Objects only
Performance Faster Slower
Syntax Simple Object-oriented
Flexibility Less More
🧠 How to Answer in Interview:
“Array is used when the size is fixed and performance matters.
ArrayList is better when we need dynamic memory, and built-in methods like add(), remove(), contains()
make it easier to work with collections.”
1. What is the Object Class?
In Java, the Object class is the parent class of all classes — whether built-in or user-defined.
📌 If you create any class, it implicitly inherits from Object.
java
CopyEdit
class Abinaya { } // internally: class Abinaya extends Object
So, every object in Java has access to methods defined in the Object class.
✅ 2. Why is Object class important?
Provides basic functionalities common to all Java objects
You can override some methods (like toString(), equals(), etc.)
Helps with debugging, comparison, cloning, hashing, etc.
✅ 3. Commonly Used Methods of Object Class
Method Purpose
toString() Returns string representation of object
equals() Compares two objects
hashCode() Returns object's hash value
getClass() Returns runtime class
clone() Creates a copy of the object
finalize() Called before garbage collection
wait(), notify(), notifyAll() Used for thread communication (in
multithreading)
✅ 4. Important Object Methods Explained
🔹 toString()
Default: Prints class name + hashcode
Override: Gives custom string for object
java
CopyEdit
public class Employee {
String name = "Abi";
public String toString() {
return "Employee Name: " + name;
public static void main(String[] args) {
Employee e = new Employee();
System.out.println(e); // prints: Employee Name: Abi
🔹 equals(Object obj)
Default: Compares memory address
Override: Compare values
java
CopyEdit
String s1 = new String("Abi");
String s2 = new String("Abi");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
✅ Interview Tip: Use .equals() for value comparison, not ==.
🔹 hashCode()
Returns integer hash of the object (used in HashMap, Set)
java
CopyEdit
String s = "Abi";
System.out.println(s.hashCode()); // same for same content
🔹 getClass()
Returns the class at runtime
java
CopyEdit
Student s = new Student();
System.out.println(s.getClass().getName()); // output: Student
🧠 Real-Time Usage in Testing
Use Case Object Method
Logging test data toString()
Comparing test results equals()
Working with collections hashCode()
Reflection utilities getClass()
💬 Interview Questions – Object Class
🔹 Q1: What is the Object class?
Answer:
Object is the superclass of all Java classes. All classes either directly or indirectly inherit it.
🔹 Q2: Why do we override toString()?
Answer:
To give a custom string representation of an object. Otherwise, it shows memory-like info
(ClassName@Hashcode).
🔹 Q3: Difference between == and .equals()?
== equals()
Compares memory address Compares values (if overridden)
Used for primitives Used for objects
🔹 Q4: When is hashCode() used?
Answer:
In hashing-based collections like HashMap, HashSet.
If you override .equals(), you should also override .hashCode().
🔹 Q5: What is clone() method?
Answer:
Used to make a copy of an object. The class must implement Cloneable.
🔹 Q6: What does finalize() do?
Answer:
It's called before the object is garbage collected. But it's deprecated now (not recommended).
🔹 Q7: Are Object class methods inherited by all Java classes?
Answer:
✅ Yes. Whether you declare it or not, all classes extend Object either directly or indirectly.
✅ Summary Table
Method Purpose Overridden?
toString() Print object in readable form ✅ Yes
equals() Compare object content ✅ Yes
hashCode() Used in collections ✅ Yes
getClass() Get runtime class info ❌ No
clone() Make object copy ❌ (with interface)
finalize() Before GC (not used now) ❌ Deprecated