Only for job seakers

Interview Question for Software Engineer(java)

what is the difference between string buffer and string object?SRING OBJECTS ARE IMMUTABLE WHILE STRING BUIDER is mutable

Explain final, finalized and finally keywords in java.
final used for define constant
finalized used before execute sytem.gc() to free the non java resoures from the object going to be delete.

what are enumerators? Enumerators are constant value set. ex. for a T shirt size it can be(small, medium,large)

explain what is parse by reference and parse by value?
Objects are doing pass by reference which is pass the memory location and string and number are pass by value which is just pass the copy of it.

what is the difference between C and Java?

what is the difference between Java servlet engine and web server?

what is static?

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.
The static variable gets memory only once in the class area at the time of class loading.
The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.

A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.

Why is the Java main method static?
It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.

Java static block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.

Expalin JSP Life cycle?

1.Jsp page translation - The container validates the syntactic correctness of the JSP pages and tag files.
2.JSP page compilation - The generated java servlet file is compiled into a java servlet class.
3.Class loading - The java servlet class that was compiled from the JSP source is loaded into the container.
4 . Execution phase -


Data base

what is a trigger? 
The statements specified in the SQL trigger are executed each time an SQL insert, update, or delete operation is performed.
 
what is a view?
view doesn't exist physically and view is a virtual table. we can create view using two or more tables or existing views.

what is a transaction in database?
A transaction, in the context of a database, is a logical unit that is independently executed for data retrieval or updates. Experts talk about a database transaction as a “unit of work” that is achieved within a database design environment.

In relational databases, database transactions must be atomic, consistent, isolated and durable summarized as the ACID acronym. Engineers have to look at the build and use of a database system to figure out whether it supports the ACID model or not. Whenever a user stores or manages data in the database, the user is making a “database transaction”.  The database transaction refers to the work done within a database management system or less likely against a database.

what do group by and having clauses?
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.


Dynamic Binding
In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method. Dynamic binding is also called Late binding.Dynamic Binding: 

Difference between == and equals()
Both equals() method and the == operator are used to compare two objects in Java.  But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. 
Whenever we create an object using the operator new, it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.

semaphore 
A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread. Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly.

How to make a class immutable
  • Make the class final
  • Make all fileds private and final
  • Do not provide setters for the variables
  • Initialize all the fileds via a constructor
  • Perform cloning of object in the getter methods to rerun a copy rather than returning actual object
Singleton class
  • Private constructor
  • Private static instance varible
  • static getter to return the instance and if the instance is null then create a new and return that. 
What is immutable - Immutable is unchangable or unmodifierble. String is immutable and main reason to make String immutable is security purpose. Once created they cannot be modified.

What is done by String inturn() intern is creating the object in the string connection pool if that string litereal is not in the string pool.

String s1 = "code";
String s2 =  new String("code");
String s3 = s2.intern();

Then s1== s3 is true

String colection pool is not eligible for garbage collection

String s1 = new String("see"); how many object will it create? 2 object, one in the heap for new key ward and onother in String connection pool created by JVM to use for future need.


Optional object in java: Optional object help developrs to get rid of null point exception/no such method exception. Optional object provide isProvide() isEmpty method, ofNullable() methods to get rid from those exception

EX: 
Optional<Customer> cusName = repo.findById() ;

cusName.isPresentOrElse(n -> System,out.println("cusname is "+ n), () -> System,out.println("cusname is not present");



Thread 

A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in a different stack frame. A process may contain multiple threads. Threads share the process resources, but still, they execute independently.

Differentiate between process and thread

A Program in the execution is called the process whereas; A thread is a subset of the process
Processes are independent whereas threads are the subset of process.
Process have different address space in memory, while threads contain a shared address space.
Context switching is faster between the threads as compared to processes.
Inter-process communication is slower and expensive than inter-thread communication.
Any change in Parent process doesn't affect the child process whereas changes in parent thread can affect the child thread.
Multithreading is a process of executing multiple threads simultaneously. Multithreading is used to obtain the multitasking. It consumes less memory and gives the fast and efficient performance. Its main advantages are:
Threads share the same address space.
The thread is lightweight.
The cost of communication between the processes is low.

Multithreading allows an application/program to be always reactive for input, even already running with some background tasks
Multithreading allows the faster execution of tasks, as threads execute independently.
Multithreading provides better utilization of cache memory as threads share the common memory resources.
Multithreading reduces the number of the required server as one server can execute multiple threads at a time.

The process of communication between synchronized threads is termed as inter-thread communication.

What are the states in the lifecycle of a Thread?
  • New: In this state, a Thread class object is created using a new operator, but the thread is not alive. Thread doesn't start until we call the start() method.
  • Runnable: In this state, the thread is ready to run after calling the start() method. However, the thread is not yet selected by the thread scheduler.
  • Running: In this state, the thread scheduler picks the thread from the ready state, and the thread is running.
  • Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.
  • Dead/Terminated: A thread is in terminated or dead state when the run() method exits.
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.

What is context switching?
In Context switching the state of the process (or thread) is stored so that it can be restored and execution can be resumed from the same point later. Context switching enables the multiple processes to share the same CPU.

Thread can be created by;
extending the Thread class
implementing the Runnable interface

The primary differences between both the ways are given below:

  • By extending the Thread class, we cannot extend any other class, as Java does not allow multiple inheritances while implementing the Runnable interface; we can also extend other base class(if required).
  • By extending the Thread class, each of thread creates the unique object and associates with it while implementing the Runnable interface; multiple threads share the same object
  • Thread class provides various inbuilt methods such as getPriority(), isAlive and many more while the Runnable interface provides a single method, i.e., run().

Can we call the run() method instead of start()?
Yes, calling run() method directly is valid, but it will not work as a thread instead it will work as a normal object. There will not be context-switching between the threads. When we call the start() method, it internally calls the run() method, which creates a new stack for a thread while directly calling the run() will not create a new stack.

Is it possible to start a thread twice?
No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead state. Therefore, if we try to start a thread twice, it will give a runtimeException "java.lang.IllegalThreadStateException". Consider the following example.

What about the daemon threads?
The daemon threads are the low priority threads that provide the background support and services to the user threads. Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. There are two methods for daemon thread available in the Thread class:

public void setDaemon(boolean status): It used to mark the thread daemon thread or a user thread.
public boolean isDaemon(): It checks the thread is daemon or not.

What does 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. Join method is overloaded in Thread class in the following ways.

Describe the purpose and working of sleep() method.
The sleep() method in java is used to block a thread for a particular time, which means it pause the execution of a thread for a specific time. There are two methods of doing so.

What is shutdown hook?
The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can use it to perform clean up the resource or save the state when JVM shuts down normally or abruptly.

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

To prevent thread interference.
To prevent consistency problem.
When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence to remove this issue, Java uses the process of synchronization which allows only one thread to be executed at a time.

Synchronization can be achieved in three ways:
by the synchronized method
by synchronized block
by static synchronization

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

What is the deadlock?
Deadlock is a situation in which every thread is waiting for a resource which is held by some other waiting thread. In this situation, Neither of the thread executes nor it gets the chance to be executed. Instead, there exists a universal waiting state among all the threads. Deadlock is a very complicated situation which can break our code at runtime.

How to detect a deadlock condition? How can it be avoided?
We can detect the deadlock condition by running the code on cmd and collecting the Thread Dump, and if any deadlock is present in the code, then a message will appear on cmd.

Ways to avoid the deadlock condition in Java:

Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock occurs when we provide locks to various threads so we should give one lock to only one thread at some particular time.
Avoid unnecessary locks: we must avoid the locks which are not required.
Using thread join: Thread join helps to wait for a thread until another thread doesn't finish its execution so we can avoid deadlock by maximum use of join method.

What is Thread Scheduler in java?
In Java, when we create the threads, they are supervised with the help of a Thread Scheduler, which is the part of JVM. Thread scheduler is only responsible for deciding which thread should be executed. Thread scheduler uses two mechanisms for scheduling the threads: Preemptive and Time Slicing.

How is the safety of a thread achieved?
If a method or class object can be used by multiple threads at a time without any race condition, then the class is thread-safe. Thread safety is used to make a program safe to use in multithreaded programming. It can be achieved by the following ways:

Synchronization
Using Volatile keyword
Using a lock based mechanism
Use of atomic wrapper classes

What is race-condition?
A Race condition is a problem which occurs in the multithreaded programming when various threads execute simultaneously accessing a shared resource at the same time. The proper use of synchronization can avoid the Race condition.

Message Passing:
Message Passing in terms of computers is communication between processes. It is a form of communication used in object-oriented programming as well as parallel programming. Message passing in Java is like sending an object i.e. message from one thread to another thread. It is used when threads do not have shared memory and are unable to share monitors or semaphores or any other shared variables to communicate. Suppose we consider an example of producer and consumer, likewise what producer will produce, the consumer will be able to consume that only. We mostly use Queue to implement communication between threads.Object based programming support message passing.

What Is Git?
Git is a distributed version control system - which just means that when you do a git clone (+url of your repository) what you are actually getting is a complete copy of your entire history of that project. This means all your commits! Woot!

GIT vs SVN

The difference between Git and SVN version control systems is that Git is a distributed version control system, whereas SVN is a centralized version control system. Git uses multiple repositories including a centralized repository and server, as well as some local repositories. 
Advantages of GIT

Git has a staging area. This just means that if you made 100 new changes to your code, you can break these 100 changes into 10 or 20 or more commits each with their own comments and their own detailed explanation of what just happened! Not only can you stage your commits out to logically display what changes were made, but you can also do patch staging that ask you if you want


Dependency Inversion Principle vs Dependency Injection
Dependency Inversion Principle is related to Dependency Injection as it applies to the Spring Framework, and you would be correct. Uncle Bob Martin coined this concept of Dependency Inversion before Martin Fowler coined the term Dependency Injection. The two concepts are highly related. Dependency Inversion is more focused on the structure of your code, its focus is keeping your code loosely coupled. On the other hand, Dependency Injection is how the code functionally works. When programming with the Spring Framework, Spring is using Dependency Injection to assemble your application. Dependency Inversion is what decouples your code so Spring can use Dependency Injection at run time.

Load balancing 
In computing, load balancing refers to the process of distributing a set of tasks over a set of resources (computing units), with the aim of making their overall processing more efficient. Load balancing techniques can optimize the response time for each task, avoiding unevenly overloading compute nodes while other compute nodes are left idle.
A load balancer is a device that acts as a reverse proxy and distributes network or application traffic across a number of servers. Load balancers are used to increase capacity (concurrent users) and reliability of applications.