Step 2 Core Java Level II 1
Step 2 Core Java Level II 1
How can memory leaks occur in Java even we have automatic garbage collection?
Memory leaks in Java occur when objects are no longer needed but still referenced
from other reachable objects, and hence preventing the garbage collector from
reclaiming their memory.
Java Fundamentals
1. Using simple, non-object types like integers and booleans helps Java run faster
and use less memory.
2. The mix of features allows Java to work well with other technologies and
systems, which might not be fully object-oriented.
public makes this method accessible from anywhere, static means I don't need
to create an object to call this method, void means it doesn't return any value, and main is
the name of this method.
The String[] args part is an array that holds any command-line arguments passed to the
program. So, when I run a Java program, this is the first method that gets called
If I don't declare the main method as static in a Java program, the JVM won't be able to
launch the application.
As aresult, the program will compile, but it will fail to run, giving an error like "Main
method is not static in class myClass, please define the main method as: public static
void main(String[] args)."
The static method in java is associated with class whereas the non-static method is
associated with an object. Static belongs to the class area, static methods don’t need an
object to be called.
Whats the difference between primitive data types and non primitive data types ?
Primitive data types in Java are the basic types of data predefined by the language and
named by a keyword. They have a fixed size and are not objects. Examples include int,
double, char, and boolean.
Non-primitive data types, on the other hand, are objects and classes that are not defined by
Java itself but rather by the programmer or the Java API. They can be used to call methods
Can you explain the difference between unboxing and autoboxing in Java?
Autoboxing automatically converts a primitive type (like int) to its corresponding wrapper
class (Integer). Unboxing does the reverse, converting an Integer back to an int.
Can you explain the role of each try, catch, and finally block in exception handling?
try block conatins code that might throw exceptions. catch handles those exceptions. finally
executes code after try/catch, regardless of an exception, typically for cleanup.
What happens if a return statement is executed inside the try or catch block? Does
the finally block still execute?
The finally block executes even if a return statement is used in the try or catch block,
ensuring cleanup runs.
Is it possible to execute a program without a catch block? If so, how would you use
try and finally together?
Yes, we can use try with finally without a catch block to ensure cleanup occurs even
if we allow the exception to propagate up.
Can you tell me a condition where the finally block will not be executed?
The finally block will not execute if the JVM exits via System.exit() during try or catch
execution.
What is the exception and the differences between checked and unchecked
exceptions?
Exception is the unwanted even that occurs during the execution of program and
disrupts the flow.
Checked exceptions must be declared or handled (IOException); unchecked do not
need to be declared or caught (NullPointerException).
Are there any scenarios where using the string pool might not be beneficial?
It will not be beneficial when there are a lot of uique string because it will be
complex situate to check each string.
How does StringBuilder differ from StringBuffer, and when should each be used?
StringBuilder is similar to StringBuffer but is not thread-safe, making it faster for
single-threaded scenarios.
Can you provide examples of when to use each type of access modifier?
1. Public: Used when members should be accessible from any other class.
2. Protected: Ideal for members that should be accessible to subclasses and classes
within the same package.
3. Default: Use when members should be accessible only within the same package.
4. Private: Best for members intended only for use within their own class.
Why do we use getters setter when we can make fields publick and setting getting
directly?
Using getters and setters instead of public variables allows us to control how values are
set and accessed, add validation, and keep the ability to change how data is stored
without affecting other parts of your program.
What are the methods available in the Object class, and how are they used?
The key methods are equals(), hashCode(), toString(), clone(), finalize(), wait(), notify(),
and notifyAll(). These provide basic operations like equality checks, memory
management, and thread coordination.
Can you provide examples of where abstraction is effectively used in Java libraries?
Java uses abstraction in its collection tools. For example, when you use a List, you
don't need to know how it stores data, whether as an ArrayList or a LinkedList.
Can you provide examples of when to use an interface versus when to extend a
class?
Use an interface when we want to list the methods a class should have, without
detailing how they work. Use class extension when we want a new class to inherit
features and behaviors from an existing class and possibly modify them.
Can an interface in Java contain static methods, and if so, how can they be used?
Yes, interfaces in Java can have static methods, which you can use without creating
an instance of the class.
When would you use an interface, and when would you use an abstract class?
Use an interface when you need multiple classes to share a contract without
implementation. Use an abstract class when you need shared behavior (method
implementations) along with method declarations.
How does the concept of default methods in interfaces help resolve the diamond
problem?
Default methods allow interfaces to provide method implementations, and in case of
conflicts (multiple interfaces with the same default method), the implementing class
must override the method, resolving ambiguity.
How can you prevent certain fields from being serialized in Java?
You can prevent specific fields from being serialized by marking them with the
transient keyword. When a field is declared as transient, it is excluded from the
serialization process, meaning its value will not be saved when the object is
serialized.
How does the Java compiler determine which overloaded method to call?
When we call an overloaded method, the Java compiler looks at the number and
type of arguments you've provided and picks the method that matches these
arguments best.
Is it possible to overload methods that differ only by their return type in Java?
In Java, we cannot overload methods just by changing their return type. The
methods must differ by their parameters for overloading to be valid.
What are the rules and conditions for method overriding in Java?
In Java, method overriding occurs when a subclass has a method with the same name, return
type, and parameters as one in its parent class. The method in the subclass replaces the one
in the parent class when called.
What happens if you attempt to use the "super" keyword in a class that doesn't
have a superclass?
If we attempt to use the "super" keyword in a class that doesn't have a superclass, a
compilation error occurs. The "super" keyword is only applicable within subclasses to
refer to members of the superclass.
What are some common use cases for using final variables in Java programming?
Common use cases for using final variables in Java programming include defining
constants, parameters passed to methods, and local variables in lambdas or
anonymous inner classes.
How does the "final" keyword contribute to immutability and thread safety in
Java?
The "final" keyword contributes to immutability and thread safety in Java by
ensuring that the value of a variable cannot be changed once assigned, preventing
unintended modifications and potential concurrency issues.
Java 8 Basics
Can you tell me some new features that were introduced in Java 8?
Lambda Expressions, Stream API, Method References , Default Methods , Optional Class,
New Date-Time API are the new features that were introduced in java 8
Why optional class, lambda expressions and stream API were introduced in java 8?
Optional class was introduced in Java 8 as a way to address the problem of null
references
Lambda expressions were introduced in Java 8 to make it easier to write code for
interfaces that have only one method, using a simpler and more direct style.
The Stream API was introduced in Java 8 to help developers process collections of
data in a more straightforward and efficient way, especially for bulk operations like
filtering or sorting.
Can you tell me some new features that were introduced in Java 11?
HTTP Client, Epsilon Garbage Collector, Z Garbage Collector, Local-Variable Syntax
for Lambda Parameters are some of the new features and along with these new
features, isBlank(), strip(), stripLeading(), stripTrailing(), and repeat() were also
introduced for strings
Can you tell me some new features that were introduced in Java 17?
Sealed Classes, Pattern Matching for switch, Foreign Function and Memory API are
some of the examples
In which scenarios would you prefer traditional for loops and streams?
Use traditional loops for simple, small datasets requiring maximum performance.
Use Streams for more complex data transformations or when working with large
datasets where readability, maintainability, and potential parallelism are prioritized.
Collection Framework
What is collection framework in java?
The Java Collection Framework is a set of tools that helps us organize, store, and manage
groups of data easily. It includes various types of collections like lists, sets, and maps.
Can you explain how Iterator works within the Java Collection Framework?
An Iterator is a tool in the Collection Framework that lets you go through a
collection's elements one by one.
How do you choose the right collection type for a specific problem?
To pick the right collection type, think about what we need: List if you want an
ordered collection that can include duplicates, Set if you need unique elements,
Queue for processing elements in order, and Map for storing pairs of keys and
values.
We use LinkedList where you frequently add and remove elements from the beginning or
middle of the list, such as implementing queues or stacks.
We use HashSet where we need to ensure that there are no duplicates and we require fast
lookups, additions, and deletions. It is ideal for scenarios like checking membership
existence, such as in a set of unique items or keys.
Can you describe how hashCode() and equals() work together in a collection
hashCode() determines which bucket an object goes into, while equals() checks
equality between objects in the same bucket to handle collisions, ensuring that each
key is unique.
Why is it important to override the hashCode method when you override equals?
What would be the consequence if we don’t?
Overriding hashCode() is crucial because hash-based collections like HashMap and
HashSet use the hashcode to locate objects. Without consistent hashCode() and
equals(), objects may not be found or stored correctly.
Can you give an example where a TreeSet is more appropriate than HashSet?
A TreeSet is more appropriate than a HashSet when you need to maintain the
elements in a sorted order. For example, if we are managing a list of customer
names that must be displayed alphabetically, using a TreeSet would be ideal.
A HashMap in Java stores key-value pairs in an array where each element is a bucket. It uses
a hash function to determine which bucket a key should go into for efficient data retrieval. If
two keys end up in the same bucket, a Collison happened then the HashMap manages these
collisions by maintaining a linked list or a balanced tree depend upon the java version in
each bucket.
What happens when two keys have the same hash code? How would you handle
this scenario?
When two different Java objects have the same hashcode, it's called a hash collision.
In this case, Java handles it by storing both objects in the same bucket in a hash-
based collection, like a HashMap. It then compares the objects using the equals()
method to differentiate them.
1. Insertion:
2. Average: O(1)
3. Worst case: O(n) when rehashing occurs
4. Deletion:
5. Average: O(1)
6. Worst case: O(n) when rehashing occurs
7. Retrieval:
8. Average: O(1)
9. Worst case: O(n) when rehashing occurs (due to hash collisions)
What techniques did hashMap, treeMap, hashSet and TreeSet uses internally for
performing operations?
HashMap uses an array of nodes, where each node is a linked list or Tree depend
upon the collisions and java versions ( From Java 8 onwards, if there is high hash
collisons then linkedList gets converted to Balanced Tree).
Can you list and explain a few common design patterns used in Java programming?
Common design patterns in Java:
1. Singleton: Ensures a class has only one instance, with a global access point.
2. Observer: Allows objects to notify others about changes in their state.
3. Factory Method: Delegates the creation of objects to subclasses, promoting
flexibility.
Which design pattern would you use to manage database connections efficiently in
a Java application?
The Singleton pattern is commonly used to manage database connections, ensuring
a single shared connection instance is reused efficiently.
How do you choose the appropriate design pattern for a particular problem in
Java?
Understand the problem fully, identify similar problems solved by design patterns,
and consider the implications of each pattern on the application’s design and
performance.
'S' stands for Single Responsibility Principle: It means a class should only have one reason
to change, meaning it should handle just one part of the functionality.
For Example: A class VehicleRegistration should only handle vehicle registration details. If it
also takes care of vehicle insurance, then it will violates this.
'O' stands for Open/Closed Principle: It means Classes should be open for extension but
closed for modification.
For Example: We have a VehicleService class that provides maintenance services. Later, we
need to add a new service type for electric vehicles and if without modifying VehicleService,
we are able to extend it from a subclass ElectricVehicleService then it follows this priciple.
'L' stands for Liskov Substitution Principle: It means Objects of a superclass should be
replaceable with objects of its subclasses without affecting the program’s correctness.
For Example: If we have a superclass Vehicle with a method startEngine(), and subclasses
like Car and ElectricCar, we should be able to replace Vehicle with Car or ElectricCar in our
system without any functionality breaking. If ElectricCar can't implement startEngine()
because it doesn’t have a traditional engine, it should still work with the interface to not
break the system.
'I' for Interface Segregation Principle: It means do not force any client to depend on
methods it does not use; split large interfaces into smaller ones.
For Example: Instead of one large interface VehicleOperations with methods like drive,
refuel, charge, and navigate, split it into focused interfaces like Drivable, Refuelable, and
Navigable. An ElectricCar wouldn't need to implement Refuelable, just Chargeable and
Navigable.
'D' stands for Dependency Inversion Principle: It means High-level modules should not
depend directly on low-level modules but should communicate through abstractions like
interfaces.
For Example: If a VehicleTracker class needs to log vehicle positions, it shouldn't depend
directly on a specific GPS device model. Instead, it should interact through a GPSDevice
interface, allowing any GPS device that implements this interface to be used without
changing the VehicleTracker class.
What is the difference between Thread class and Runnable interface in Java?
The Thread class defines a thread of execution, whereas the Runnable interface
should be implemented by any class whose instances are intended to be executed by
a thread.
Can you describe a scenario where you would use wait() and notify() methods in
thread communication?
Use wait() and notify() for inter-thread communication, like when one thread needs
to wait for another to complete a task before proceeding.
Can we create a server in java application without creating spring or any other
framework?
Yes, you can create a server in a Java application using only Java SE APIs, such as by
utilizing the ServerSocket class for a simple TCP server or the HttpServer class for
HTTP services.
What is the difference between Young Generation and Old Generation memory
spaces?
The Young Generation stores newly created objects. The Old Generationholds
objects that have survived several garbage collection cycles in the Young Generation