Synechron Java Interview Questions and answers for( 2–4 Experience)
“Hello everyone, in this article, I will be sharing interview questions and answers from Synechron Tech Company for the role of a Java Developer. Let’s dive in.”
Are you preparing for a job interview as a Java developer?
Find my book Guide To Clear Java Developer Interview here Gumroad(PDFFormat) and Amazon (Kindle eBook).
Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDFFormat) and Amazon (Kindle eBook).
Guide To Clear Front-End Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).
Download the sample copy here:
Guide To Clear Java Developer Interview[Free Sample Copy]
Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]
Guide To Clear Front-End Developer Interview [Sample_Copy]
Ready for personalized guidance? Book your 1-on-1 session with me here: https://topmate.io/ajay_rathod11
What is Stream API in java? how it works internally?
The Stream API in Java is a feature introduced in Java 8. It provides a new abstraction called Stream that lets you process data in a declarative way. The Stream API is used for processing collections of objects, allowing for complex operations to be performed in a sequence of steps.
A Stream in Java is a sequence of elements supporting sequential and parallel aggregate operations. These operations can be filtering, mapping, sorting, or other manipulations of data.
Here’s how it works internally:
- Creation: A Stream is created on a source, which could be an array, a collection, or an I/O channel. The source is wrapped into a Stream object.
- Configuration: The Stream object is configured with a series of transformations. These transformations are not applied immediately but are instead stored as a pipeline of operations. Each operation is a function that takes a Stream as input and produces a Stream as output.
- Execution: When a terminal operation (like
collect
,reduce
,forEach
, etc.) is invoked on the Stream object, the processing starts. The data is piped through all the operations in the pipeline, one element at a time. The operations are processed in a "lazy" manner, meaning they're only executed when necessary. - Consumption: The Stream is consumed and cannot be used again. If you need to traverse the data again, you’ll need to create a new Stream.
List<String> names = Arrays.asList("John", "Jane", "Adam", "Eve");
List<String> uppercaseNames = names.stream() // create a Stream
.filter(name -> name.startsWith("A")) // filter names that start with "A"
.map(String::toUpperCase) // convert to uppercase
.collect(Collectors.toList()); // collect results into a list
In this example, the Stream API is used to filter a list of names and convert them to uppercase. The filter
and map
methods are intermediate operations that configure the Stream, and the collect
method is a terminal operation that triggers the processing and collects the results into a new list.
What is solid principles with examples?
SOLID is an acronym for a set of five principles that help in designing software systems that are easy to maintain and extend over time. Here they are with examples:
- Single Responsibility Principle (SRP): A class should have only one reason to change. It means a class should only have one job or responsibility.
- Example: If you have a
User
class, it should only be responsible for things directly related to the user. It shouldn't be responsible for, say, loading user data from a database. That should be the responsibility of a separateUserRepository
class. - Open-Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. This means you should be able to add new functionality without changing existing code.
- Example: If you have a
Shape
class and you want to add a new shape, you should be able to do this by adding a new class that inherits fromShape
, without modifying theShape
class or any other existing classes. - Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types. This means that if a program is using a base class, it should be able to use any of its subclasses without the program knowing or behaving incorrectly.
- Example: If you have a
Bird
class with a methodfly()
, and aPenguin
class that inherits fromBird
but doesn't support thefly()
method, then you're violating LSP. A solution could be to have a separateFlyingBird
class for birds that can fly. - Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use. This means that a class should not have to implement methods it doesn’t use.
- Example: If you have an
IPrinter
interface with methodsprint()
,fax()
, andscan()
, and aSimplePrinter
class that only supports printing, then you're violating ISP. A solution could be to have separate interfaces forIPrinter
,IFax
, andIScanner
. - Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. This means that you should depend on abstractions, not on concrete implementations.
- Example: If you have a
NotificationService
class that directly uses theEmailService
class to send emails, then you're violating DIP. A solution could be to have anIMessageService
interface thatEmailService
implements, andNotificationService
should depend onIMessageService
, not onEmailService
directly.
Remember, these principles are guidelines, not hard rules. There might be situations where it makes sense to violate a principle in order to achieve some other goal. However, understanding these principles can help you design more maintainable and extensible software.
What are the new classes introduced in java 8 can you name them?
Java 8 introduced several new classes and interfaces, especially in the java.util.function
, java.util.stream
, and java.time
packages. Here are some of the key ones:
- Functional Interfaces in
java.util.function
package:
Predicate<T>
Function<T,R>
Consumer<T>
Supplier<T>
UnaryOperator<T>
BinaryOperator<T>
- Stream API classes and interfaces in
java.util.stream
package:
Stream<T>
IntStream
LongStream
DoubleStream
Collector<T,A,R>
Collectors
Date and Time API classes in java.time
package:
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
Period
Duration
Instant
ZoneId
Optional class in java.util
package:
Optional<T>
New JavaScript Engine class in jdk.nashorn.api.scripting
package:
NashornScriptEngineFactory
These new classes and interfaces provide a lot of powerful new capabilities, such as functional programming, stream processing, and a much improved date and time API.
What is the difference between Wait and join method in multithreading?
wait()
and join()
are two methods used in multithreading in Java, and they serve different purposes:
- wait(): This method is defined in the
Object
class and it's used for inter-thread communication. When a thread executes a call towait()
, it goes into a state of dormancy and releases the lock it holds on the object so that other threads can take control of the lock and begin executing their own critical sections. The thread remains dormant untilnotify()
ornotifyAll()
is called on the same object.
Example:
synchronized(object) {
while(<condition does not hold>)
object.wait();
// proceed with the logic
}
join(): This method is defined in the Thread
class and it's used to pause the current thread until the specified thread dies. In other words, if a thread A
calls join()
on a thread B
, A
will wait until B
completes its execution.
Example:
Thread t1 = new Thread(new MyRunnable());
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// continue with the logic after t1 has finished
In summary, wait()
is used for inter-thread communication and it releases the lock on the object, while join()
is used to wait for a thread to die and it doesn't release any lock.
they have asked Array based program, write down using lamba(don't remember the exact question)
What will happen Obj.wait method without synchronisation and 4 threads operating on it without notify method?
If you call wait()
on an object without synchronizing on that object first, you will get an IllegalMonitorStateException
at runtime. This is because wait()
, notify()
, and notifyAll()
methods are designed to be used in a multithreaded environment to achieve synchronization, and they can only be called from within a synchronized context.
Here’s what the Java documentation says about wait()
:
The current thread must own this object’s monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object’s monitor to wake up either through a call to the notify()
method or the notifyAll()
method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
So, if you have 4 threads operating on an object and you call wait()
without a synchronized block or method, you'll get an IllegalMonitorStateException
.
Furthermore, if you don’t call notify()
or notifyAll()
, any thread that is waiting on the object will remain in the waiting state indefinitely, because there's nothing to notify it to wake up. This could lead to a situation where a thread is permanently waiting, often referred to as thread starvation.
Write a linked list data structure program in java?
Diffrence between Springboot and spring?
Spring Framework and Spring Boot are both Java frameworks used for building enterprise-grade applications. They are related but serve different purposes.
Spring Framework: This is a comprehensive framework used for building Java applications. It provides a wide range of functionality including dependency injection, aspect-oriented programming, data access, transaction management, MVC for web applications, and more. However, setting up a project using Spring Framework can be complex because you need to handle a lot of configurations manually.
Spring Boot: This is a project built on top of the Spring Framework. It simplifies the setup and development of Spring applications by providing defaults for code configuration, reducing the effort needed to get a Spring application up and running. It also provides a standalone server (Tomcat, Jetty, or Undertow) so you can run Spring applications directly from your main method, and it has a lot of additional features to simplify the deployment and monitoring of your application.
Here are some key differences:
- Configuration: Spring requires a lot of manual configuration for setup. Spring Boot, on the other hand, provides automatic configuration to reduce this complexity.
- Project Setup: Setting up a project in Spring can be a bit complex and requires a deep understanding of its internals. Spring Boot makes this process easy with its Spring Initializr web-based project generator.
- Standalone: Spring Boot applications can be packaged as jar which includes an embedded server. This is not the case for a traditional Spring MVC application where you need to deploy your application on a separate server.
- Dependency Management: Spring Boot provides a starter POMs feature to simplify Maven configuration and dependency management.
- Production-Ready: Spring Boot provides features like health checks and metrics out of the box which makes it production-ready.
What is Microservices and whats the use?
If my hashcode returns the same hashcode what will happen, employee class as object i am passing as key?
If your hashCode()
method in the Employee
class always returns the same value, it doesn't mean you will lose data or get incorrect results. However, it will degrade the performance of your hash-based collections like HashMap
, HashSet
, etc.
Here’s why:
In a HashMap
, for example, the hashCode()
is used to determine the bucket where the key-value pair should be stored. If every key has the same hashcode, they will all go into the same bucket. This turns the HashMap
into a linked list in terms of performance, because all entries will be stored as a chain of nodes in that single bucket. This means that every lookup, insertion, or deletion will require a linear search through all the entries, which is very inefficient.
When you use an object as a key in a HashMap
, it's important to correctly override both hashCode()
and equals()
. The hashCode()
method should be designed to distribute keys evenly across the buckets for better performance, and equals()
should be used to determine the equality of keys.
So, while returning the same hashcode won’t cause data loss or incorrect results, it will lead to poor performance when using hash-based collections.
There were few questions on ConcurrentHashmap and other type of concurrent collection?
How to optimise performance of application and what will you do how will you take thread dump what are the tools?
Optimizing the performance of an application involves several steps:
- Profiling: Identify the bottlenecks in your application. This could be CPU usage, memory leaks, slow database queries, etc. Tools like VisualVM, JProfiler, or YourKit can be used for profiling Java applications.
- Optimize Code: Look for inefficient code and try to optimize it. This could involve using more efficient data structures, reducing the time complexity of algorithms, reducing database calls, etc.
- Concurrency: Use multithreading where appropriate to make use of multiple cores and perform tasks in parallel.
- Caching: Implement caching to store the result of expensive operations, to avoid repeating them when the same inputs occur again.
- Database Optimization: Optimize your database queries, use indexing, and normalize or denormalize your database as needed.
- Use of Latest Libraries/Frameworks: Always try to use the latest libraries or frameworks as they usually come with performance improvements.
To take a thread dump:
- jstack: This is a command-line utility that comes with the JDK. You can use it to take a thread dump of a running Java application. The command is
jstack <pid>
, where pid is the process id of the Java application. - VisualVM: This is a graphical tool that can be used to monitor a running Java application. It can also be used to take a thread dump.
- JConsole: This is another graphical tool that comes with the JDK. It can be used to monitor a running Java application and take a thread dump.
Stream based questions what are the type of streams in java-8?
In Java 8, the term “streams” usually refers to a new abstraction introduced in the java.util.stream package, which allows you to perform functional-style operations on streams of elements. The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
There are three types of Streams available in Java 8:
- Sequential Stream: A sequential stream has a single pipeline and can process the elements only in sequence. It’s created by default when you call the
stream()
method.
List<String> list = Arrays.asList(“A”, “B”, “C”);
Stream<String> stream = list.stream();
Parallel Stream: A parallel stream has multiple pipelines and can process the elements in parallel, which can be faster than a sequential stream for large datasets on a multi-core machine. It’s created when you call the parallelStream()
method.
List<String> list = Arrays.asList(“A”, “B”, “C”);
Stream<String> parallelStream = list.parallelStream();
Infinite Stream: These are streams that don’t have a fixed size, as in they can keep on growing. The Stream.iterate
and Stream.generate
methods can be used to create infinite streams.
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
Each type of stream is designed for a different kind of operation. Sequential and parallel streams are typically used with a finite number of elements, while infinite streams are used for generating a sequence of values on the fly.
What is Join method in multithreading?
its execution. If t
is a Thread
object whose thread is currently executing, then t.join()
causes the current thread to pause its execution until t
's thread terminates.
Here’s a simple example:
Thread t1 = new Thread(new MyRunnable());
t1.start();
try {
t1.join(); // The current thread will wait until t1 finishes its execution
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Continue with the logic after t1 has finished
In this example, the current thread will wait for t1
to finish its execution before it continues. This can be useful in cases where you want to start another thread to perform some task, but you need the results of that task before you can proceed.
There are also overloaded versions of join()
that allow you to specify a maximum amount of time that you're willing to wait for the other thread to finish:
join(long millis)
Waits at mostmillis
milliseconds for this thread to die.join(long millis, int nanos)
Waits at mostmillis
milliseconds plusnanos
nanoseconds for this thread to die.
If the thread doesn’t finish in that time, the join()
call will return anyway, and the current thread will continue its execution.
What is Objects class?
The Objects
class, introduced in Java 7, is a utility class that provides static methods to operate on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, comparing two objects, etc.
Here are some of the commonly used methods from the Objects
class:
equals(Object a, Object b)
: Checks if two objects are equal according to their equals()
method. This method is null-safe, meaning if both objects are null, it returns true, and if one is null, it returns false.
Objects.equals(“test”, new String(“test”)); // returns true
Objects.equals(null, “test”); // returns false
Objects.equals(null, null); // returns true
hashCode(Object o)
: Returns the hash code of a non-null argument and 0 for a null argument. Useful for null-safe hash code calculation.
Objects.hashCode(null); // returns 0
Objects.hashCode(“test”); // returns hash code of the string “test”
toString(Object o)
: Returns the result of calling toString
for a non-null argument and "null" for a null argument.
Objects.toString(null); // returns “null”
Objects.toString(“test”); // returns “test”
requireNonNull(T obj)
: Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors.
Objects.requireNonNull(null); // throws NullPointerException
Objects.requireNonNull(“test”); // returns “test”
compare(T a, T b, Comparator<? super T> c)
: Compares two objects with a given Comparator
, and is null-safe.
The Objects
class helps in writing cleaner and more robust code by providing null-safe methods.
Difference between Flat vs Flat-map?
flat
and flatMap
are operations that are used on collections or streams of data. The difference between them lies in how they handle nested structures.
- Flat: The
flat
operation (not available in Java, but exists in some other languages) typically takes a structure that has multiple layers of nesting, and reduces one layer of nesting. It "flattens" the structure by one level. For example, if you have a list of lists, aflat
operation would give you a single list that contains all the elements of the inner lists. - FlatMap: The
flatMap
operation is a combination of amap
and aflat
operation. It first applies a function to each element in the structure (likemap
does), but then it flattens the result. This is useful when the function you want to apply to each element produces a collection or a stream itself.
Here’s an example in Java:
List<String> list = Arrays.asList("Hello World", "Java Stream");
// map operation
List<String[]> mapResult = list.stream()
.map(s -> s.split(" "))
.collect(Collectors.toList());
// flatMap operation
List<String> flatMapResult = list.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.collect(Collectors.toList());
In this example, the map
operation splits each string into an array of words, so it produces a List<String[]>
. The flatMap
operation also splits each string into words, but it flattens the result into a List<String>
where each word is an individual element.
So, the key difference is that flatMap
can handle situations where you want to transform each element in your stream into multiple elements (or none at all), and you want to end up with a flat stream of results, not a nested structure.
What are the types of blocking queue in multithreading?
In Java, the java.util.concurrent
package provides several types of blocking queues that are useful for multithreading. A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full.
Here are the types of blocking queues in Java:
ArrayBlockingQueue: A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The ‘bounded’ means that it cannot store more than a fixed number of elements.
lockingQueue: An optionally-bounded blocking queue based on linked nodes. The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. Without a capacity constraint, linked queues typically hold more elements than array-based queues.
PriorityBlockingQueue: An unbounded blocking queue that uses the same ordering rules as class PriorityQueue
and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion.
DelayQueue: An unbounded blocking queue of Delayed
elements, in which an element can only be taken when its delay has expired.
SynchronousQueue: A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one.
LinkedTransferQueue: An unbounded TransferQueue based on linked nodes. This queue orders elements FIFO (first-in-first-out) with respect to any given producer.
LinkedBlockingDeque: An optionally-bounded blocking deque based on linked nodes.
Each type of blocking queue has its own specific use cases in multithreaded programming, depending on the requirements of the task at hand.
Looking for more transcript !! here are the links
IBM Java Developer Interview 0–3 years of Experience 2024
Citi Bank Java developer Interview Question for 5+ Experienced Professional
HSBC Java Interview Experience with Q&A for 0–5 years of Experience
Cisco Java Developer Interview Transcript 2024(Java,Spring-Boot,Hibernate)
Thanks for reading
- 👏 Please clap for the story and follow me 👉
- 📰 Read more content on my Medium (60 stories on Java Developer interview)
Find my books here: