java que tl
java que tl
System.out.println(s1 == s2);//true
System.out.println(s1 == s3); //false
System.out.println(s1.equals(s2));//t
System.out.println(s1.equals(s3));//t
Key Differences
Aspect: Static Members Non-Static Members
Belongs To: Class Object
Access: Via class name or object Only via object
Memory Allocation: Once per class Once per object
Lifetime: As long as the class is loaded As long as the object
exists
Keyword: Declared with static No static keyword
6) An abstract class can extend another Java class and implement multiple Java
interfaces.
An interface can extend another Java interface only.
8) A Java abstract class can have class members like private, protected, etc.
Members of a Java interface are public by default.
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Java automatically finds and deletes unused objects from the heap to reclaim
memory.
Developers don’t need to manually free memory.
Note: System.gc() and Runtime.gc() are the methods which requests for Garbage
collection to JVM explicitly
but it doesn’t ensures garbage collection as the final decision of garbage
collection is of JVM only.
unchecked:
Definition: These are exceptions that are not checked by the compiler at compile
time.
They are runtime exceptions and typically occur due to programming
errors.
Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException.
Thread: A thread is like a small unit of a program that can run independently. A
program can have one or more threads.
The volatile keyword ensures that changes to a variable made by one thread are
visible to all other threads immediately.
In Java, streams are used to handle input and output operations like reading from
or writing to files,
network connections, and other data sources. Streams in Java are part of the
java.io and java.nio packages,
and they abstract the handling of data, allowing for smooth data flow between
programs and external sources.
...........---JDBC---.........
1.What is JDBC? Explain its architecture.
JDBC (Java Database Connectivity) is a Java API that provides a standard interface
for connecting to and
interacting with databases. It allows Java applications to execute SQL queries,
retrieve results,
and update data in relational databases. JDBC enables Java programs to communicate
with a variety of
database management systems (DBMS), such as MySQL, Oracle, SQL Server, etc.
work flow:
1.Load Driver → 2. Establish Connection → 3. Create Statement → 4. Execute Query →
5. Process Results → 6. Close Connection.
---------------------------------------------------------------
3.Create a Statement
After establishing the connection, you need to create a Statement or
PreparedStatement object to execute SQL queries.
The DriverManager class in Java is part of the JDBC (Java Database Connectivity)
API. Its main purpose
is to manage a list of database drivers that Java applications use to connect to
different databases.
3)Manage Driver List: It keeps track of all the drivers and automatically selects
the correct one for the connection.
How It Works:
When you call DriverManager.getConnection(), it checks the list of available
drivers and uses the correct
one to establish a connection to the database.
-----------------------------------------------
-----------------------------------------------------------------------------------
---------
5.What are prepared statements, and why are they used?
prepared statements is
a feature where the database pre-compiles SQL code and stores the results,
separating it from data.
Benefits of prepared statements are: efficiency, because they can be used
repeatedly without re-compiling.
secure and flexibility.
-----------------------------------------------------------------------------------
-------------
Executing a stored procedure in Java is done using the JDBC API, specifically
through the CallableStatement interface.
Stored procedures are precompiled SQL routines stored in the database that can be
invoked by Java applications.
-----------------------------------------------------------------------------------
----------
7. What is a transaction in JDBC? How do you manage it?
you can use the Connection interface's setAutoCommit() method to set the auto-
commit mode to false.
Once auto-commit is disabled, you can use the commit() and rollback() methods to
commit or roll back a transaction.
-----------------------------------------------------------------------------------
-------------------
Batch processing in JDBC is a feature that allows executing multiple SQL statements
as a single batch,
reducing the number of database interactions. It is particularly useful for
performing large-scale,
repetitive operations like inserting, updating, or deleting records in bulk.
4)Handle Results:
Check the return values of executeBatch() to determine the outcome of each
statement
-----------------------------------------------------------------------------------
-------------
In Java, SQL exceptions are instances of the SQLException class, thrown when a
database access error or
other issues related to database operations occur. Handling these exceptions
properly ensures the application remains
robust and can recover gracefully from errors.
Message: e.getMessage()
SQLState: e.getSQLState()
Error Code: e.getErrorCode()
----data structures----
10.reverse linked list code?
// Node class to represent each element in the LinkedList
class Node {
int data; // Data to store in the node
Node next; // Reference to the next node in the list
System.out.println("Original List:");
list.display(); // Output: 10 -> 20 -> 30 -> 40 -> 50 -> null
list.reverse();
System.out.println("Reversed List:");
list.display(); // Output: 50 -> 40 -> 30 -> 20 -> 10 -> null
}
}
___________________________________________________________________________________
__
-----oops-----
26. Can a class extend multiple classes in Java? Why or why not?
No, a class in Java cannot extend multiple classes directly. This is because Java
does not support
multiple inheritance with classes to avoid ambiguity and complexity that can arise
from it.
Instead, Java allows a class to implement multiple interfaces, which provides a way
to achieve
multiple inheritance in a safer and more structured manner.
-----------------------------------------------------------------------------------
-----------
27. What is the difference between IS-A and HAS-A relationships
IS a Definition: Represents inheritance. It signifies that one class (child) is a
type of another class (parent).
HAS a Definition: Represents composition or aggregation. It signifies that one
class contains an instance
of another class as part of its properties.
-----------------------------------------------------------------------------------
----
28. What are inner classes in Java?
In Java, inner classes are classes defined within another class. They are used to
logically group classes
that belong together and to improve encapsulation. An inner class has access to
the members
(including private members) of its enclosing class.
Method hiding in Java occurs when a static method in a subclass has the same
signature as a static method
in its superclass. In this case, the method in the subclass hides the method in the
superclass, rather than
overriding it. The method that gets called is determined at compile-time, based on
the type of the reference,
not the object.
-----------------------------------------------------------------------------------
----------
Anonymous classes in Java are a type of local inner class that do not have a name.
They are defined and instantiated in a single expression, typically used for
creating one-time-use objects or
overriding methods of an existing class or interface.
-----------------------------------------------------------------------------------
---------------
___________________________________________________________________________________
_______________________
-----Advance java----- .
The Java Native Interface (JNI) is a framework that enables Java code to interact
with or call native
applications and libraries written in other programming languages like C, C++, or
assembly. It acts as a bridge
between Java and native code, allowing Java applications to use functionalities not
directly available in Java.
Components of JNI:
Native Libraries: The shared libraries (.dll on Windows, .so on Linux, .dylib on
macOS) that contain
the native methods.
Java Code: Declares the native methods using the native keyword.
Runnable:
Does not return any result.
The run() method has a void return type.
Callable:
Can return a result after the task is executed.
The call() method returns a value of a generic type (T).
-----------------------------------------------------------------------------------
-------------
Java Remote Method Invocation (RMI) is a mechanism that allows an object in one
Java virtual machine (JVM) to access and invoke an object in another JVM. RMI is
used to build distributed applications and enables remote communication
between Java programs.
-----------------------------------------------------------------------------------
---------
65. How does the ExecutorService framework work?
3)Task Execution:
The executor picks tasks from a queue and assigns them to threads in the pool. If
all threads are busy,
the tasks wait in the queue.
4)Result Handling:
For tasks submitted with "Callable" or "Runnable", the result can be retrieved
using a "Future" object.
The Future allows:
Blocking until the task completes.
Cancelling a task.
Checking if a task is done.
5)Shutdown:
shutdown(): Prevents new tasks from being submitted but allows previously submitted
tasks to complete.
shutdownNow(): Attempts to stop all running tasks immediately.
-----------------------------------------------------------------------------------
---------
66. What are annotations in Java?
The Java Fork/Join framework is a tool for parallel programming that uses a
"divide and conquer" strategy to break down complex tasks into smaller, more
manageable subtasks.
1)Submit a Task:
A large task is submitted to the ForkJoinPool.
Example: Summing an array of integers.
3)Process Subtasks:
Subtasks are executed in parallel by the worker threads in the pool.
4)Combine Results:
Results of subtasks are combined using the "join()" method.
----------------------------------------------------------------------------
68.How does the Java NIO package differ from the IO package?
Java IO package for handling input and output. While both packages serve the
purpose of reading and
writing data,they differ significantly in terms of design, functionality, and
performance.
........spring framework.......
The Spring Framework is a widely used, open-source framework for building Java
applications.
It provides comprehensive infrastructure support for developing robust and scalable
enterprise applications.
-----------------------------------------------------------------------------------
--------
82. Explain dependency injection and inversion of control?
Dependency Injection (DI): is a design pattern used in software development to
achieve "loose coupling"
between components. It involves injecting required dependencies (objects) into a
class rather than
the class creating or managing them itself.
83. What are Spring beans, and how are they configured?
In the Spring Framework, a bean is an object that is managed by the Spring IoC
(Inversion of Control) container.
Beans represent the building blocks of a Spring application, and the container
handles their lifecycle,
configuration, and dependencies.
1. XML-Based Configuration
Beans are defined in an XML file, typically "applicationContext.xml".
2. Annotation-Based Configuration
Spring provides annotations like "@Component, @Service, @Repository, and
@Controller" to define beans.
3. Java-Based Configuration
Use a class annotated with "@Configuration" to define beans programmatically
@Component
Definition:
A generic stereotype for any Spring-managed component.
It is the base annotation for @Service and @Repository.
@Service
Definition:
A specialization of @Component used to denote "service layer" classes.
Indicates that the class contains business logic or service-related operations.
@Repository
Definition:
A specialization of @Component for "persistence layer" classes.
Often used with DAO (Data Access Object) or "repository" patterns.
Automatically integrates exception translation for database-related exceptions into
Spring's
"DataAccessException".
Spring Boot is a framework built on top of the Spring Framework. It makes it easy
to create standalone,
production-ready Java applications by reducing the need for complex configurations.
1.Purpose:
2.Configuration:
3.Startup Process:
4.Focus Area:
Spring MVC: Specialized for "web applications" using the MVC pattern.
Spring Boot: Suitable for "microservices", standalone apps, and any Spring-based
application.
-----------------------------------------------------------------------------------
---------
Instead of writing the same code in multiple places, you can define it once as an
aspect and apply
it automatically to the relevant parts of the application.
In simple terms, Spring AOP helps you add extra behavior to your
application without changing its main functionality.
-----------------------------------------------------------------------------------
---------
Verifies the identity of users, ensuring that they are who they say they are.
Supports various authentication methods, such as "username/password, OAuth, LDAP,
JWT, and form-based login"
3.Session Management:
Manages user sessions and provides features like session fixation protection,
session expiration,
and concurrent session control.
-----------------------------------------------------------------------------------
------------------
Spring handles REST APIs by providing flexible and powerful tools such as:
To build a REST API using Spring Boot, you can follow these steps:
1.Set up your project
2.Create the data model
3.Create the repository
4.Create the service layer
5.Create the controller
6.Configure the application properties
7.Run the application
-----------------------------------------------------------------------------------
---------------
___________________________________________________________________________________
_____________________