Java 3.pdf
Java 3.pdf
In Java, an abstract class is a class that cannot be instantiated on its own and is meant to be
extended by other classes. It may contain abstract methods (methods without implementation)
and concrete methods (methods with implementation). Abstract classes provide a way to define
common behaviors and enforce a contract for subclasses.
1.
Abstract methods: These are methods declared without a body (implementation) in the
abstract class. Subclasses are required to provide an implementation for these methods, unless
the subclass is also abstract.
2.
Concrete methods: An abstract class can have fully implemented methods. These methods
can be used by the subclasses without needing to override them.
void eat() {
System.out.println("This animal eats.");
}
}
3.
Constructors: Abstract classes can have constructors, which can be called when a subclass
object is created. However, an abstract class itself cannot be instantiated directly.
@Override
void sound() {
System.out.println("Bark");
}
}
Fields (Instance variables): Abstract classes can have instance variables (fields), and these
fields can be inherited by the subclasses.
Animal(String name) {
this.name = name;
}
}
@Override
void sound() {
System.out.println(name + " barks.");
}
}
5.
Abstract class can extend other classes: Abstract classes can also inherit other abstract or
concrete classes.
@Override
void feedYoung() {
System.out.println("Nursing puppies.");
}
}
6.
Abstract methods in an abstract class: If a class contains an abstract method, the class itself
must be declared abstract.
void sleep() {
System.out.println("Animal is sleeping.");
}
}
7.
An abstract class can implement interfaces: Just like regular classes, abstract classes can
implement interfaces. If an abstract class implements an interface, it doesn't need to provide
implementations for all the methods of the interface (as long as the abstract class itself is
abstract).
interface AnimalBehavior {
void eat();
void sleep();
}
@Override
public void eat() {
System.out.println("Dog eats.");
}
}
8.
1. Code reuse: Abstract classes allow you to define methods that can be shared by all
subclasses, reducing duplication. Common behavior can be implemented in the abstract
class, while specialized behavior is left for subclasses to define.
2. Enforcing a contract: Abstract classes are useful when you want to define common
functionality across subclasses but require each subclass to implement specific
methods.
● Abstract Class:
○ Can have both abstract and concrete (implemented) methods.
○ Can have constructors and instance variables.
○ Can inherit from other classes (abstract or concrete).
○ A class can extend only one abstract class (single inheritance).
● Interface:
○ All methods are abstract by default (except static or default methods in Java 8+).
○ Cannot have instance variables (only constants, i.e., public static final
fields).
○ Can only inherit from other interfaces (supports multiple inheritance).
○ A class can implement multiple interfaces (multiple inheritance).
Example:
interface AnimalBehavior {
void eat();
void sleep();
}
Animal(String name) {
this.name = name;
}
@Override
void sound() {
System.out.println(name + " barks.");
}
@Override
public void eat() {
System.out.println(name + " eats.");
}
}
● Partial implementation: Allows common functionality in the abstract class while leaving
some methods for subclasses to implement.
● Consistency: Enforces a consistent structure across subclasses (via abstract methods).
● Code reusability: Allows subclasses to reuse common logic.
Let me know if you'd like to dive deeper into any aspect of abstract classes!
Interface in JAVA
In Java, an interface is a reference type, similar to a class, but it is used to define a contract or
a set of methods that a class must implement. Unlike classes, interfaces cannot contain any
concrete (implemented) methods (except for default and static methods in Java 8 and later).
Interfaces are used to represent the capability or behavior of an object.
1. Methods in Interfaces:
Abstract methods: By default, all methods in an interface are abstract, meaning they do not
have an implementation. A class that implements the interface must provide concrete
implementations for these methods.
interface Animal {
void sound(); // Abstract method
}
Default methods (Java 8+): Starting with Java 8, interfaces can have default methods, which
are methods with a body. These methods have a default implementation, and classes that
implement the interface are not required to override them (though they can).
interface Animal {
void sound(); // Abstract method
Static methods: Interfaces can also have static methods with a body. These methods must be
called using the interface name and cannot be overridden by implementing classes.
interface Animal {
static void breathe() {
System.out.println("The animal is breathing.");
}
}
○
2. Fields (Constants):
Static final fields: All fields in an interface are implicitly public, static, and final (i.e.,
constants). These constants must be initialized when they are declared.
interface Animal {
int LEGS = 4; // Implicitly public static final
}
○
3. No Constructors:
An interface can extend one or more other interfaces. A class can implement multiple interfaces
(Java supports multiple inheritance through interfaces).
interface Animal {
void sound();
}
○
5. Implementing an Interface:
A class implements an interface using the implements keyword. It must provide concrete
implementations for all abstract methods in the interface (unless the class is abstract).
interface Animal {
void sound();
}
○
6. Access Modifiers:
All methods in an interface are implicitly public, so you don't need to explicitly declare them as
public. Similarly, fields are public static final by default.
interface Animal {
// Implicitly public
void sound();
}
○
7. Multiple Interface Implementation:
A class can implement multiple interfaces, which is Java's way of supporting multiple
inheritance. However, it can only extend one class (since Java supports single inheritance for
classes).
interface Animal {
void sound();
}
interface Walkable {
void walk();
}
1. Decoupling:
○ Interfaces are commonly used to define public APIs for libraries or frameworks.
By defining interfaces, you allow users to implement their own versions of
behavior.
Example of Interface Usage:
// Defining an interface
interface Animal {
void sound(); // Abstract method
Method Methods are abstract by default Can have both abstract and
Implementation (can have default and static concrete methods
methods from Java 8)
Constructor Cannot have constructors Can have constructors
Fields All fields are implicitly public Can have any type of fields
static final (instance, static, etc.)
Access Modifiers All methods are public by default Methods can have any access
modifier (public, protected,
private)
Use Case Used to define a contract for Used to provide a common base
classes for classes that share common
behavior
interface Walkable {
void walk();
}
interface Animal {
void sound();
Interfaces can also define static methods, which are not inherited by implementing classes.
They must be called using the interface name.
interface Animal {
static void breathe() {
System.out.println("Breathing...");
}
}
Let me know if you need further details or examples on any specific topic related to interfaces in
Java!
Ah, I see! You’re asking about interfaces provided by Hibernate. Let me explain the interfaces
in Hibernate, which are used for interacting with Hibernate's core functionality, including
managing sessions, transactions, and querying the database.
Hibernate provides a variety of interfaces that you can use to interact with the ORM framework
and manage entities, sessions, and other components. Here's an overview of some important
interfaces in Hibernate:
1. Session Interface
● The Session interface is the primary interface used for interacting with the database in
Hibernate. It is responsible for handling all interactions with the persistent data, including
CRUD operations and queries.
● It manages the lifecycle of persistent entities (objects) during the session.
Common Methods:
Example:
transaction.commit();
session.close();
2. SessionFactory Interface
Common Methods:
Example:
3. Transaction Interface
Common Methods:
4. Query Interface
● The Query interface represents a Hibernate query, allowing you to execute database
queries in HQL (Hibernate Query Language) or SQL.
● It can be used to retrieve entities or scalar values from the database.
Common Methods:
Example:
Common Methods:
Example:
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.eq("firstName", "John"));
List<Person> persons = criteria.list();
6. Configuration Interface
● The Configuration interface is used to configure Hibernate settings and build the
SessionFactory. It allows you to specify mappings, properties, and other settings for
Hibernate.
Common Methods:
Example:
7. Transaction Interface
● The CriteriaBuilder interface is part of the JPA Criteria API, which Hibernate also
implements. It allows you to create type-safe, dynamic queries that are based on the
object model.
● It is more modern and flexible compared to the old Hibernate Criteria API.
Common Methods:
● createQuery(): Creates a query object.
● createCriteria(): Creates a new Criteria object.
Common Methods:
Example:
● Hibernate also supports JTA (Java Transaction API) for distributed transactions. The
TransactionManager interface is used in environments where multiple resource
managers (such as databases, message queues, etc.) are involved in a distributed
transaction.
These interfaces are at the core of Hibernate's functionality and are essential for performing
most operations related to persistence, transactions, and querying.
Absolutely! When working with Spring Boot, both JPQL (Java Persistence Query Language)
and HQL (Hibernate Query Language) are commonly used to query data in a database. These
two query languages are closely related, as HQL is specific to Hibernate (an implementation of
JPA), and JPQL is the standardized query language used in JPA.
Since Spring Boot can work with both JPA and Hibernate, you’ll often use JPQL when working
with Spring Data JPA, but you can also use HQL if you're directly working with Hibernate.
Let’s break down how JPQL and HQL are used in Spring Boot:
Spring Boot, by default, uses Spring Data JPA to simplify working with JPA repositories. When
using Spring Data JPA, JPQL is commonly used for querying entities.
Key Points:
● JPQL is used for querying entities in a database and works with Java objects.
● Spring Data JPA makes it easier to work with JPQL by providing repository interfaces.
● JPQL queries are defined as methods in repository interfaces or custom queries
using @Query.
First, you need to define an entity class, which represents a table in your database.
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Now, create a repository interface that extends JpaRepository. This repository will provide
basic CRUD operations automatically.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
// Define custom JPQL queries below
}
You can define custom JPQL queries either by using method naming conventions or @Query
annotation.
Spring Data JPA generates the JPQL queries based on method names. For example:
This method will automatically generate a JPQL query to find all Person entities with the given
lastName:
You can define custom JPQL queries using the @Query annotation in your repository interface:
public interface PersonRepository extends JpaRepository<Person, Long> {
Now, you can call this repository method in the service layer:
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
For a query that finds all Person entities with a specific firstName:
This is how you write JPQL queries in Spring Boot using Spring Data JPA.
HQL is used when you're directly working with Hibernate. If you're using Spring Boot with
Hibernate as the JPA provider, you can use HQL queries in the same way as JPQL.
Spring Data JPA provides a more abstracted approach, but you can still use HQL in custom
queries when you directly interact with Hibernate (if you’re not using Spring Data JPA's
JpaRepository).
If you want to use HQL specifically, you might write a custom query using Session or Query
from Hibernate.
You can use Session to create and execute an HQL query directly:
import org.hibernate.Session;
import org.hibernate.query.Query;
@Service
public class PersonService {
@Autowired
private SessionFactory sessionFactory;
return query.getResultList();
}
}
In this example:
Database Uses JPA provider to interact with the Directly uses Hibernate ORM to
Access database interact with DB
Usage in Spring Typically used with Spring Data JPA Used directly when working with
Boot and JpaRepository Hibernate
Query Syntax Similar to SQL but works with entities Similar to SQL but works with
(Java classes) entities (Java classes)
Annotations Uses @Query for custom queries in Uses Session and Query for
Spring Data JPA custom queries in Hibernate
Conclusion:
● JPQL is ideal when using Spring Boot with Spring Data JPA because it abstracts
much of the interaction with the underlying database. It's more flexible and decouples
the code from the persistence layer.
● HQL is used when you're working directly with Hibernate, which is often useful for
advanced queries or if you need access to Hibernate-specific features.
In most Spring Boot applications, you'll likely stick to JPQL (via Spring Data JPA) because it's
more portable, but HQL can still be used for specific scenarios where you're working directly
with Hibernate.
SQL Questions: -
Here’s a list of common SQL interview questions that cover basic to advanced concepts.
These questions will help you prepare for a variety of SQL-related interviews:
Basic SQL Questions:
1. What is SQL?
○ INNER JOIN: Returns records that have matching values in both tables.
○ LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table, and
the matched records from the right table. If there’s no match, NULL values are
returned for columns from the right table.
4. What is a primary key?
○ A primary key is a field (or combination of fields) that uniquely identifies each
record in a table. It must contain unique values and cannot contain NULL values.
5. What is a foreign key?
○ A foreign key is a field in one table that uniquely identifies a row in another table.
It is used to establish and enforce a link between the data in the two tables.
6. What is the difference between WHERE and HAVING clause?
○ DELETE: Removes rows from a table but can be rolled back. It is slower
because it logs each row deletion.
○ TRUNCATE: Removes all rows from a table but cannot be rolled back. It is faster
because it doesn’t log individual row deletions.
10. What are aggregate functions in SQL?
○ The GROUP BY clause is used to group rows that have the same values into
summary rows. It is commonly used with aggregate functions like COUNT(),
SUM(), AVG(), MAX(), and MIN().
4. What is the difference between RANK() and DENSE_RANK()?
○RANK(): Assigns a rank to each row within the partition of the result set, with
gaps in ranking when there are ties.
○ DENSE_RANK(): Similar to RANK(), but does not leave gaps when there are
ties.
5. What are subqueries in SQL?
○A self join is a regular join but the table is joined with itself. This can be useful for
hierarchical data.
8. What is a view in SQL?
○ A view is a virtual table based on the result set of an SQL query. It does not store
data physically but can be queried like a real table.
9. Explain CASE statement in SQL.
Example:
SELECT firstName,
lastName,
CASE
WHEN age < 18 THEN 'Minor'
ELSE 'Adult'
END AS age_group
FROM person;
10.
11. What is the difference between CHAR and VARCHAR?
○ A stored procedure is a set of SQL statements that can be stored and executed
on the database server. It allows for modular and reusable code.
2. What is a trigger in SQL?
Example:
9.
10. Explain the difference between CLUSTERED and NON-CLUSTERED indexes.
○ CLUSTERED Index: The data is stored in the order of the index. There can only
be one clustered index per table.
○ NON-CLUSTERED Index: The index is stored separately from the data, and
there can be multiple non-clustered indexes on a table.
11. What is database partitioning?
These are just a few of the common SQL interview questions that you might encounter. Be sure
to practice with sample queries and understand the underlying concepts to confidently answer
SQL questions during interviews! Let me know if you'd like more details or have any other
questions.
To find the highest salary of an employee in SQL, you can use the MAX() aggregate function,
which returns the maximum value from a column.
Explanation:
● MAX(salary): This function will return the highest salary from the salary column.
● FROM employees: This indicates that we are selecting from the employees table.
● AS highest_salary: This gives a label (alias) to the column returned by the MAX()
function.
If you want to find the employee(s) with the highest salary, you can use a
subquery:
SELECT employee_id, employee_name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
Explanation:
This will return the details (like employee_id, employee_name, and salary) of all employees
who have the highest salary. If there are multiple employees with the same highest salary, they
will all be included.
To find the second highest salary in SQL, you can use several methods. Here are a few
common approaches:
This is a simple way to find the second highest salary by first finding the highest salary and then
finding the highest salary that's less than the maximum.
1. The subquery (SELECT MAX(salary) FROM employees) finds the highest salary.
2. The main query retrieves the maximum salary that is less than the highest salary,
effectively giving the second-highest salary.
If you're using a database that supports the LIMIT clause (like MySQL, PostgreSQL, SQLite),
you can use the ORDER BY to sort the salaries in descending order and then limit the results.
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Explanation:
● ORDER BY salary DESC: This sorts the salary column in descending order.
● LIMIT 1 OFFSET 1: This skips the first record (highest salary) and returns the second
record (second-highest salary).
In databases that support window functions like ROW_NUMBER(), you can assign a rank to each
salary and then filter for the second-highest one.
WITH RankedSalaries AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank
FROM employees
)
SELECT salary
FROM RankedSalaries
WHERE rank = 2;
Explanation:
1. ROW_NUMBER() OVER (ORDER BY salary DESC): This assigns a unique row
number to each record based on the salary column in descending order.
2. The common table expression (CTE) RankedSalaries is used to generate the rank.
3. The main query retrieves the salary where the rank is 2, which corresponds to the
second-highest salary.
If you have multiple employees with the same salary, you can use DENSE_RANK() to assign
ranks and get the second highest salary, even in the case of ties.
WITH RankedSalaries AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
)
SELECT salary
FROM RankedSalaries
WHERE rank = 2;
Explanation:
Summary of Methods:
Choose the method based on your SQL database and your specific requirements (e.g., handling
ties).
Explanation:
● MIN(salary): The MIN() function will return the lowest salary from the salary
column.
● FROM employees: This indicates that we are selecting from the employees table.
● AS lowest_salary: This gives an alias to the column returned by the MIN() function
for clarity.
If you want to find the employee(s) who have the lowest salary, you can use a subquery:
Explanation:
If there are multiple employees with the same lowest salary, this query will return all of them.
To find the second minimum salary of an employee in SQL, you can use several approaches.
Here are a few common methods:
Explanation:
If you're using databases that support the LIMIT clause (like MySQL, PostgreSQL, or SQLite),
you can sort the salaries and limit the result to skip the first one.
SELECT salary
FROM employees
ORDER BY salary ASC
LIMIT 1 OFFSET 1;
Explanation:
If your database supports window functions like ROW_NUMBER(), you can assign a row number
to each salary in ascending order and then filter for the second row.
WITH RankedSalaries AS (
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary ASC) AS rank
FROM employees
)
SELECT salary
FROM RankedSalaries
WHERE rank = 2;
Explanation:
If there are duplicate salaries, DENSE_RANK() can help assign ranks without skipping any
numbers for ties.
WITH RankedSalaries AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary ASC) AS rank
FROM employees
)
SELECT salary
FROM RankedSalaries
WHERE rank = 2;
Explanation:
● DENSE_RANK() OVER (ORDER BY salary ASC): This assigns a rank to each salary
in ascending order. It doesn't skip ranks for tied salaries.
● The query retrieves the salary with rank 2, which is the second distinct minimum salary.
Summary of Methods:
1. Subquery with MIN(): Works across most databases and is simple to use.
2. ORDER BY with LIMIT and OFFSET: Best for MySQL, PostgreSQL, SQLite.
3. Window Function (ROW_NUMBER()): Best for SQL Server, PostgreSQL, and Oracle.
4. Window Function (DENSE_RANK()): Best for handling duplicate salaries in SQL
Server, PostgreSQL, and Oracle.
Choose the method that best fits your database and requirements.
Let me know if you need further details or help with a specific approach!
Certainly! In SQL, joins are used to combine data from two or more tables based on a related
column. Joins are essential when working with normalized databases where data is split across
multiple tables.
1. INNER JOIN:
An INNER JOIN returns rows that have matching values in both tables. If a row in one table
does not have a corresponding row in the other table, it is excluded from the result set.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Example:
employees table:
1 John 101
2 Sarah 102
3 Tom 103
4 Emma 101
departments table:
department_id department_nam
e
101 Sales
102 HR
103 IT
Now, to get a list of employees along with their department names, you can use an INNER
JOIN:
Result:
employee_nam department_nam
e e
John Sales
Sarah HR
Tom IT
Emma Sales
In this example, we only get employees who have a matching department_id in the
departments table.
A LEFT JOIN returns all rows from the left table (table1), and the matched rows from the right
table (table2). If there is no match, the result will contain NULL for columns from the right table.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example:
Let’s use the same employees and departments tables, but this time we’ll get all employees
and include department names, even if the employee is not assigned to a department.
Result:
employee_nam department_nam
e e
John Sales
Sarah HR
Tom IT
Emma Sales
If there were an employee with a department_id that doesn't exist in the departments
table, the result would have NULL in the department_name column.
A RIGHT JOIN returns all rows from the right table (table2), and the matched rows from the left
table (table1). If there is no match, the result will contain NULL for columns from the left table.
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Example:
If we want to make sure we get all departments, including departments that have no employees,
we use a RIGHT JOIN.
Result:
employee_nam department_nam
e e
John Sales
Sarah HR
Tom IT
Emma Sales
NULL Finance
In this example, the Finance department does not have any employees, so employee_name
is NULL.
A FULL JOIN returns rows when there is a match in one of the tables. It returns all rows from
both tables, with NULL where there is no match.
Syntax:
SELECT columns
FROM table1
FULL JOIN table2
ON table1.column = table2.column;
Example:
To get a complete list of employees and departments, including employees with no departments
and departments with no employees, you can use a FULL JOIN.
Result:
employee_nam department_nam
e e
John Sales
Sarah HR
Tom IT
Emma Sales
NULL Finance
In this example, the result includes Finance, which does not have any employees, and will also
include employees who might not be assigned to a department.
5. SELF JOIN:
A SELF JOIN is a join where a table is joined with itself. This is useful when you need to
compare rows within the same table.
Syntax:
SELECT a.columns, b.columns
FROM table a, table b
WHERE a.column = b.column;
Example:
Consider a table of employees where each employee has a manager. We can use a SELF
JOIN to list employees along with their managers.
employees table:
1 John NULL
2 Sarah 1
3 Tom 1
4 Emma 2
Result:
Employe Manager
e
John NULL
Sarah John
Tom John
Emma Sarah
In this example, John is the manager of Sarah and Tom, while Sarah is the manager of Emma.
Summary of Joins:
Type of Description Includes Matching Rows from:
Join
INNER Returns only rows where there is a Both tables.
JOIN match in both tables.
LEFT Returns all rows from the left table, Left table, with NULL for no match.
JOIN matched with right table.
RIGHT Returns all rows from the right table, Right table, with NULL for no match.
JOIN matched with left table.
FULL Returns rows when there is a match in Both tables, with NULLs where no
JOIN either table. match.
SELF Joins the table with itself, typically using Same table (used for comparing rows
JOIN aliases. within the same table).