Search This Blog

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, October 15, 2023

Most Important Core Java Interview Questions Answers

 1.) What is serialization?

Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file system, or more generally, to a transmission medium or storage facility. A serializable object must implement the Serializable interface. We use Object Output Stream to write this object to a stream and Object Input Stream to read it from the stream.


2.) Is synchronized a modifier? identifier?? what is it??

It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.


3.) What is a singleton class? where is it used?

Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.


4.) Why java does not have multiple inheritance?

The Java design team strove to make Java:

• Simple, object-oriented, and familiar

• Robust and secure

• Architecture neutral and portable

• High performance

• Interpreted, threaded, and dynamic


The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object-oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple).

In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.


5.)Why java is not 100% oops?

Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question.


6.) What is a resource bundle?

In its simplest form, a resource bundle is represented by a text file containing keys and the text value for each key.


7.) What is a transient variable?

The transient variables can't be serialized. For example, if a variable is declared as transient in a Serializable class and the class is written to an Object Stream, the value of the variable can't be written to the stream instead when the class is retrieved from the Object Stream the value of the variable becomes null.


Top Most Multithreading Interview Questions and Answers

1.) What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:

Threads share the same address space.

Thread is lightweight.

The cost of communication between process is low.


2) What is the thread?

A thread is a lightweight subprocess. It is a separate path of execution. It is called a separate path of execution because each thread runs in a separate stack frame.


3)What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.


4) What does the join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.


5) What is the difference between the wait() and sleep() methods?

                            wait()                                                                       sleep()

1) The wait() method is defined in Object class.     The sleep() method is defined in the Thread class.

2) wait() method releases the lock.                             The sleep() method doesn't release the lock.


6) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If we do, it throws an exception.


7) Can we call the run() method instead of start()?

Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.


8) What about the daemon threads?

The daemon threads are basically the low-priority threads that provide the background support to the user threads. It provides services to the user threads.


9)Can we make the user thread a daemon thread if the thread is started?

No, if you do so, it will throw IllegalThreadStateException


10)What is a shutdown hook?

The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it to perform clean-up resources.


11)When should we interrupt a thread?

We should interrupt a thread if we want to break out of sleep or wait for the state of a thread.


12) What is synchronization?

Synchronization is the capability of control the access of multiple threads to any shared resource. It is used:

To prevent thread interference.

To prevent consistency problems.


13) What is the purpose of the Synchronized block?


The synchronized block is used to lock an object for any shared resource.

The scope of the synchronized block is smaller than the method.


14)Can Java objects be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.


15) What is static synchronization?

If you make any static method as synchronized, the lock will be on the class not on the object. more details...


16)What is the difference between notify() and notifyAll()?

The notify() is used to unblock one waiting thread whereas the notifyAll() method is used to unblock all the threads in the waiting state.


17)What is deadlock?

Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.


Saturday, July 10, 2021

What are Packages in core java and how to use them ?

  Java package is a technique for organizing Java classes into namespaces similar to the modules of Modula, providing modular programming in JavaJava packages can be stored in compressed files called JAR files, allowing classes to be downloaded faster as groups rather than individually.

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

Some of the existing packages in Java are::

·        java. lang - bundles the fundamental classes

·        java.io - classes for input, output functions are bundled in this package

Programmers can define their own packages to bundle groups of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a package:


When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.

 

What are Packages in java and how to use them?

 OOPS CONCEPT

Packages in Java are a mechanism to encapsulate a group of classes, interfaces, and sub-packages. Many implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize class files into packages. All we need to do is put related class files in the same directory, give the directory a name that relates to the purpose of the classes, and add a line to the top of each class file that declares the package name, which is the same as the directory name where they reside.

In java, there are already many predefined packages that we use while programming.

For example: java.langjava.iojava.util etc.


However one of the most useful features of java is that we can define our own packages


Advantages of using a package:


Before discussing how to use them Let see why we should use packages.

§  Reusability:  Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.

§  Easy to locate the files.

§  In a real-life situation, there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.


Types of packages:


1) User-defined package: The package we create is called a user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.


Defining a Package:


This statement should be used at the beginning of the program to include that program in that particular package.


package  <package name>;

 

Sunday, June 27, 2021

Most common Core Java Interview Questions

1) What is the difference between an Abstract class and an Interface?

1. Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.

2. An class can implement any number of interfaces, but subclass at most one abstract class.

3. An abstract class can have nonabstract methods. All methods of an interface are abstract.

4. An abstract class can have instance variables. An interface cannot.

5. An abstract class can define the constructor. An interface cannot.

6. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).

7. An abstract class inherits from Object and includes methods such as clone() and equals().


2) What are checked and unchecked exceptions?

Java defines two kinds of exceptions :

• Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOException.

• Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically,programming errors.


3) What is the difference between C++ & Java?

Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". 

Here are a few I discovered:

• Java is multithreaded

• Java has no pointers

• Java has automatic memory management (garbage collection)

• Java is platform-independent (Stroustrup may differ by saying "Java is a platform"

• Java has built-in support for comment documentation

• Java has no operator overloading

• Java doesn’t provide multiple inheritance.

• There are no destructors in Java


4) What are the statements in JAVA?

Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon

• Assignment expressions

• Any use of ++ or --

• Method calls

• Object creation expressions

These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.


5) What is the JAR file?

JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.

Tuesday, June 22, 2021

Roadmap of Full Stack Java Developer

Get started with the Full Stack Java Developer and explore everything about the full stack java developer.

There are a whole lot of technologies to learn and not all of them can be java based. At the very least, you will have to learn There are a whole lot of technologies to learn, and not all of it can be java based. At the very least, you will have to learn full-stack java development every beginner learns Core Java, Spring, Hibernate, Spring Boot, Microservices, SQL.

Becoming a full-stack developer seems an intimidating task, especially if you are completely new to the field of coding. As a beginner, you might think that you have a whole lot to learn within a short span of time. The languages, frameworks, libraries, and databases along with everything else required.

Phase-1: Implement OOPS using JAVA with Data Structures and Beyond

Brush up on your knowledge of software development fundamentals, Agile and Scrum methodologies, Java and data structures, GIT to manage version control systems, and Maven to manage project dependencies.

Phase-2: Become a back-end expert

Familiarize yourself with the back-end technologies by implementing knowledge of SQL, Java Servlets, and relational database ORM with Hibernate. Learn to connect databases with JDBC and work with RESTful web services.

Phase-3: Implement Frameworks the DevOps way

Master UI skills with advanced HTML and CSS and build 3-tier applications with Spring framework, Angular, JUnit5, SOAP. This phase will enable you to deploy continuous integration and automation using a common DevOps tool: Jenkins.

Phase-4: Develop a Web Application using frontend stack

Build real-world websites and applications using the front-end stack technologies such as HTML, CSS, JavaScript, and Angular. Handle diverse data types and manage your applications efficiently using MongoDB.

Phase-5: Testing in a DevOps Lifecycle

Begin automation testing and integration with Selenium Webdriver. Create seamless development and production environments using containerization with Docker and manage applications on Amazon S3 servers.

Full Stack Java Developer Capstone project provides you with hands-on working experience, the objective being to develop the entire application from scratch and deploy it into a pseudo-production environment.

Advantages:-

The advantage of being a full-stack developer is:

You can master all the techniques involved in a development project.

You can make a prototype very rapidly.

You can provide help to all the team members.

You can reduce the cost of the project.

You can reduce the time used for team communication.

You can switch between front and back-end development based on requirements.

You can better understand all aspects of new and upcoming technologies.


Saturday, October 10, 2020

JDK 1.6 features

 1. Collections Framework Enhancements:-

Java SE 6 API provides bi-directional collection access. New collection interfaces include Deque, NavigableSet, NavigableMap.

Deque: A linear collection that supports element insertion and removal at both ends. The name deque is short for "double-ended queue".This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation)

2.java.io Enhancements:-

New class” Console” is added and it contains methods to access a character-based console device. The readPassword()methods disable echoing thus they are suitable for retrieval of sensitive data such as passwords. The method System.console ()returns the unique console associated with the Java Virtual Machine.

Increased Developer Productivity

 3. GUI :

– JFC and Swing integration with desktop by using Windows API.

-Java 2D integration with desktop such as using desktop anti-aliasing font settings

– Splash screen direct support and can be shown before JVM started

– System tray support with ability to add icons, tool tips, and pop-up menus to the Windows or any other system tray (such as Gnome).

4. Security Features and Enhancements:

–  Native platform Security (GSS/Kerberos) integration.

– Java Authentication and Authorization Service (JAAS) login module that employs LDAP authentication

-New Smart Card I/O API

5. JavaTM API for XML Processing (JAXP):

The Java API for XML Processing (JAXP) enables applications to parse, transform, validate and query XML documents using an API that is independent of a particular XML processor implementation. JAXP provides a pluggability layer to enable vendors to provide their own implementations without introducing dependencies in application code. Using this software, application and tool developers can build fully-functional XML-enabled Java applications for e-commerce, application integration, and web publishing.

The Java Platform, Standard Edition version 6.0 includes JAXP 1.4. JAXP 1.4 is a maintenance release of JAXP 1.3 with support for the Streaming API for XML (StAX).

6. JDBC 4.0 Enhancements:-

Java SE 6 includes several enhancements to the Java Database Connectivity (JDBC) API. These enhancements will be released as JDBC version 4.0. The main objectives of the new JDBC features are to provide a simpler design and better developer experience


The major features added in JDBC 4.0 include:

1.Auto-loading of JDBC driver class

2.Connection management enhancements

3.Support for RowId SQL type

4.DataSet implementation of SQL using Annotations

5.SQL exception handling enhancements

 1. Auto-Loading of JDBC Driver

In JDBC 4.0, we no longer need to explicitly load JDBC drivers using Class.forName(). When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from among the JDBC drivers that were loaded at initialization and those loaded explicitly using the same class loader as the current application.

The DriverManager methods getConnection and getDrivers have been enhanced to support the Java SE Service Provider mechanism (SPM). According to SPM, a service is defined as a well-known set of interfaces and abstract classes, and a service provider is a specific implementation of a service. It also specifies that the service provider configuration files are stored in the META-INF/services directory. JDBC 4.0 drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC driver’s implementation of java.sql.Driver. For example, to load the JDBC driver to connect to an Apache Derby database, the META-INF/services/java.sql.Driver file would contain the following entry:

org.apache.derby.jdbc.EmbeddedDriver

We can simply call:

Connection conn =

DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);In JDBC 4.0, we don’t need the Class.forName() line.

2.Connection management enhancements:

Prior to JDBC 4.0, we relied on the JDBC URL to define a data source connection. Now with JDBC 4.0, we can get a connection to any data source by simply supplying a set of parameters (such as host name and port number) to a standard connection factory mechanism. New methods were added to Connection and Statement interfaces to permit improved connection state tracking and greater flexibility when managing Statement objects in pool environments. The metadata facility (JSR-175) is used to manage the active connections. We can also get metadata information, such as the state of active connections, and can specify a connection as standard (Connection, in the case of stand-alone applications), pooled (PooledConnection), or even as a distributed connection (XAConnection) for XA transactions. Note that we don’t use the XAConnection interface directly. It’s used by the transaction manager inside a Java EE application server such as WebLogic, WebSphere, or JBoss.

3.Support for RowId SQL type:

The RowID interface was added to JDBC 4.0 to support the ROWID data type which is supported by databases such as Oracle and DB2. RowId is useful in cases where there are multiple records that don’t have a unique identifier column and you need to store the query output in a Collection (such Hashtable) that doesn’t allow duplicates. We can use ResultSet’s getRowId() method to get a RowId and PreparedStatement’s setRowId() method to use the RowId in a query.

An important thing to remember about the RowId object is that its value is not portable between data sources and should be considered as specific to the data source when using the set or update methods in PreparedStatement and ResultSet respectively. So, it shouldn’t be shared between different Connection and ResultSet objects.

4.Annotation-Based SQL Queries:

The JDBC 4.0 specification leverages annotations (added in Java SE 5) to allow developers to associate a SQL query with a Java class without writing a lot of code to achieve this association. Also, by using the Generics (JSR 014) and metadata (JSR 175) APIs, we can associate the SQL queries with Java objects specifying query input and output parameters. We can also bind the query results to Java classes to speed the processing of query output. We don’t need to write all the code we usually write to populate the query result into a Java object. There are two main annotations when specifying SQL queries in Java code: Select and Update.

Here’s an example of Select annotation to get all the active loans from the loan database:

interface LoanAppDetailsQuery extends BaseQuery {

@Select(“SELECT * FROM LoanDetais where LoanStatus = ‘A’”)

DataSet<LoanApplication> getAllActiveLoans();

}

public DataSet<LoanAppDetails> getAllActiveLoans() throws Exception {

// Get Connection

Connection conn = getConnection();

LoanAppDetailsQuery query = null;

DataSet<LoanAppDetails> loanDetails = null;

query = QueryObjectFactory.createQueryObject(

LoanAppDetailsQuery.class, conn);

loanDetails = query.getAllActiveLoans();

return loanDetails;

}

Example of Update annotation:

interface LoanAppDetailsQuery extends BaseQuery {

@Update(sql=”update LoanDetails set LoanStatus = ?1

where loanId = ?2″)

boolean updateLoanStatus(String loanStatus, int loanId);

}

5.SQL Exception Handling Enhancements:

–    Support for causal relationships

–     Support for enhanced for-each loop

Ex1:     We can use getNextException() method in SQLException to iterate through the exception chain. Here’s some sample code to process SQLException causal relationships:

catch(SQLException ex) {

while(ex != null) {

LOG.error(“SQL State:” + ex.getSQLState());

LOG.error(“Error Code:” + ex.getErrorCode());

LOG.error(“Message:” + ex.getMessage());

Throwable t = ex.getCause();

while(t != null) {

LOG.error(“Cause:” + t);

t = t.getCause();

}

ex = ex.getNextException();

}

}

Ex2:

code snippet showing the enhanced for-each loop feature added in SQLException.

catch(SQLException ex) {

for(Throwable e : ex ) {

LOG.error(“Error occurred: ” + e);

}

}