Search This Blog

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

Top 5 Core Java Exception Handling interview questions and answers

  What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors. It is mainly used to handle checked exceptions.


1.) What is the difference between Checked Exception and Unchecked Exception?

1)Checked Exception:

The classes that extend the Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2)Unchecked Exception:

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.


2.) What is the base class for Error and Exception?

Throwable.


3) Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.


4.) What is finally block?

finally block is a block that is always executed. 


5.) Can finally block be used without catch?

Yes, by try block. finally must be followed by either try or catch.


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>;

 

Basics of Spring Framework

 This spring tutorial provides in-depth concepts of Spring Framework with simplified examples. It was developed by Rod Johnson in 2003. Spring framework makes the easy development of the JavaEE application.

Spring Framework

Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework, in a broader sense, can be defined as a structure where we find solutions of various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC, etc. We will learn these modules on the next page. Let's understand the IOC and Dependency Injection first.

Inversion Of Control (IOC) and Dependency Injection

These are the design patterns that are used to remove dependency from the programming code. They make the code easier to test and maintain. Let's understand this with the following code:


class Employee{  

Address address;  

Employee(){  

address=new Address();  

}  

}  


In such a case, there is the dependency between the Employee and Address (tight coupling). In the Inversion of Control scenario, we do this something like this:


class Employee{  

Address address;  

Employee(Address address){  

this.address=address;  

}  

}  


Thus, IOC makes the code loosely coupled. In such a case, there is no need to modify the code if our logic is moved to a new environment.

In the Spring framework, the IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection:

makes the code loosely coupled so easy to maintain

makes the code easy to test


Advantages of Spring Framework:

There are many advantages of the Spring Framework. They are as follows:

1) Predefined Templates-

Spring framework provides templates for JDBC, Hibernate, JPA, etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating connections, creating statements, committing transactions, closing connections, etc. You need to write the code for executing the query only. Thus, it saves a lot of JDBC code.

2) Loose Coupling-

The Spring applications are loosely coupled because of dependency injection.

3) Easy to test-

The Dependency Injection makes it easier to test the application. The EJB or Struts application requires the server to run the application but the Spring framework doesn't require a server.

4) Lightweight-

Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5) Fast Development-

The Dependency Injection feature of Spring Framework and it support to various frameworks make the easy development of the JavaEE application.

6) Powerful abstraction-

It provides a powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA, and JTA.

7) Declarative support-

It provides declarative support for caching, validation, transactions, and formatting.