CoreJava
CoreJava
CoreJava
https://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and-jre
JRE is the implementation of JVM and provides a platform for executing Java programs. JRE consists
of JVM, Java binaries, and other classes. JRE doesn't contain any development tools like Java
compiler, debugger, or JShell.
OOPS
https://raygun.com/blog/oop-concepts-java/
Composition and aggregation are two types of object-oriented relationships in Java. They are both
used to model the relationships between classes, but they have different strengths and weaknesses.
Composition is a stronger relationship than aggregation. In composition, the child object cannot exist
without the parent object. For example, a car has an engine. The engine is a part of the car, and the
car cannot run without the engine.
Aggregation is a weaker relationship than composition. In aggregation, the child object can exist
without the parent object. For example, a school has students. The students are part of the school,
but the school can still exist without the students
https://stackoverflow.com/questions/11881552/implementation-difference-between-aggregation-
and-composition-in-java
Pass by value
Yes, Java is pass-by-value. This means that when you pass a variable to a method, the value of the
variable is copied, not the variable itself.
For example, if you have a variable called x with the value 10, and you pass it to a method called
myMethod(), the method will receive a copy of the value 10, not the variable x itself.
Any changes that are made to the value of the variable inside the method will not be reflected in the
original variable x outside of the method.
This is because the method is only working with a copy of the value, not the original variable itself.
Constructor:
the default access level for a constructor in Java is the same as the default access level for a class.
This means that if a class is declared with no access modifier, then the constructor will also be
accessible to any class in the same package. The default access level is also known as the package-
private level. Compiler creates default constructor only when there are no other constructor
available for the class.
Error
After is not printing coz the app was not able to handle Error in catch block which is handling of type
Exception and after finally the exception is propagated. Finally block will be executed in case an Error
Is thrown
Advantages of autoboxing:
Prevents errors: Autoboxing allows developers to use primitive types and wrapper class
objects interchangeably, which can help prevent errors.
Less code: No need of conversion between primitives and Wrappers manually so less coding
is required
Cleaner code: Autoboxing makes code look cleaner and easier to read.
Seamless integration: Autoboxing integrates well with Java collections, which use objects
instead of primitives.
Advantages of immutability?
1. Immutable objects are thread-safe so you will not have any synchronization issues.
2. Immutable objects are good Map keys and Set elements, since these typically do not change
once created.
3. Immutability makes it easier to parallelize your program as there are no conflicts among
objects.
4. The internal state of your program will be consistent
5. References to immutable objects can be cached as they are not going to change.
ConcurrentHashMap is similar to HashMap, but it's thread-safe and allows modification while
iteration. While one thread is iterating, the remaining threads are allowed to perform any
modification in a safe manner.
Class implementing 2 interfaces having method with same name – default and abstract
Compiler will be happy even if the class implementing both interface has same method name. But
compiler will force to override the method which has abstract method and the overridden method
will take the precedence
Default vs static method in interface
difference between default methods and static methods in interfaces is the same difference there is
between a static method and an instance method in a class.
Static method in interface cannot be overridden as its final. If the default method of the interface is
overridden in the class then the overridden method of the class will take the precedence. If it’s a
static method in interface then it can only be invoked by InterfaceName and not the object
implementing interface.
To call the original method, you can use super. However, you must put the interface name before
calling super.
If two or more interfaces provide a default implementation for the same method, the implementing
class must provide its own implementation to avoid ambiguity.
A functional interface is an interface with only one abstract method. The compiler ensures that the
interface has only one abstract method when using the lambda expression for the Function
interface. If the interface has more than one abstract method, the program will show an error.
A functional interface in Java can contain any number of static and default methods, but only one
abstract method.
An overriding method can also return a subtype of the type returned by the overridden method. This
subtype is called a covariant return type.
Method overloading for null argument
https://stackoverflow.com/questions/5229809/how-to-do-method-overloading-for-null-argument
If we try to override the static method in the child class then the child's class method will get hidden
and the parent's class method will be called based on the object reference. In below example, m1 is
a static method hence the output is parent, parent, child. If it was non static method then the output
will be Parent, child, child.
For example, if you have a parent class called Animal with an instance variable called name, and a
child class called Dog that extends Animal and has an instance variable called name, the Dog class's
name variable will hide the Animal class's name variable.
This can be confusing, so it's important to be aware of it when you're writing Java code. If you need
to access the parent class's variable, you can use the super keyword. For example, you could write:
This would get the value of the Animal class's name variable, not the Dog class's name variable.
https://stackoverflow.com/questions/22581102/instance-variable-hiding-with-inheritance
https://stackoverflow.com/questions/51106740/explain-how-variable-hiding-is-working-in-this-java-
code
// The intermediate operation filter is not executed until the terminal operation is called
In this example, the filter() operation is an intermediate operation, which means that it does not
immediately process the data. Instead, it creates a “pipeline” of operations that will be performed
on the data. The pipeline is not executed until a terminal operation is called on the stream, such as
forEach() in this case.
When the forEach() method is called, the stream will start processing the data and calling the filter()
method on each element. The filter() method will then return a new stream containing only the
elements that satisfy the predicate. The forEach() method will then iterate over the new stream and
print each element to the console.
Lazy evaluation can lead to significant performance gains when working with large data sets. By only
executing the operations that are necessary, lazy evaluation can avoid unnecessary processing and
improve the overall performance of the application.
Here are some additional things to consider when deciding whether to create a checked or
unchecked exception:
Recoverability - If the client can reasonably be expected to recover from the exception, make it a
checked exception. If the client cannot do anything to recover from the exception, make it an
unchecked exception.
Severity - If the exception is severe, such as a security breach, make it a checked exception. If the
exception is not severe, such as a file not found error, make it an unchecked exception.
Frequency - If the exception is likely to occur frequently, make it a checked exception. If the
exception is unlikely to occur, make it an unchecked exception.
https://stackoverflow.com/questions/4639432/checked-vs-unchecked-exception#:~:text=All
%20Exceptions%20are%20part%20of,unchecked%20exceptions%20are%20runtime%20exceptions.
https://stackoverflow.com/questions/68514749/if-you-explicitly-throw-an-unchecked-exception-in-
your-code-isnt-it-now-a-chec
Error vs Exception
The main difference between errors and exceptions in Java is that errors are typically a result of
inadequate system resources, while exceptions occur during the execution and compilation of a
program.
Errors are usually accompanied by an error message but can also occur without any message. It's not
possible to recover from an error, and the system in which the program is running is responsible for
errors. In Java, all errors are unchecked.
Exceptions are the issues that can appear at runtime and compile time. It is possible to recover from
an exception, and the code of the program is accountable for exceptions. In Java, the exceptions can
be both checked and unchecked.
OutOfMemoryError
StackOverflowError:
NoClassDefFoundError: This error occurs when the program tries to load a class that cannot
be found.
ArithmeticException
ArrayIndexOutOfBoundsException:
FileNotFoundException
hashCode() Contract
Internal consistency: the value of hashCode() may only change if a property that is in
equals() changes
equals consistency: objects that are equal to each other must return the same hashCode
collisions: unequal objects may have the same hashCode
https://www.baeldung.com/java-equals-hashcode-contracts#:~:text=equals()%20method%20in
%20some,must%20return%20the%20same%20hashCode
https://sanjoykumarmalik.com/important-note-java-equals-method-and-inheritance/
https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-
hashcode-methods-in-java#:~:text=You%20must%20override%20hashCode(),HashMap%2C
%20HashSet%2C%20and%20Hashtable.
InstanceOf vs getClass()
instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type
on the right-hand side (RHS) or some subtype.
Hashcode implementation
https://www.baeldung.com/java-hashcode
https://stackoverflow.com/questions/16629893/good-hashcode-implementation
byte[] is a primitive data type that represents an array of 8-bit bytes. It's often used to store binary
data, such as image files or compressed data.
InputStream is an abstract class that represents a sequence of bytes. It's commonly used to read
data from a file or network connection.
Use MultipartFile if you're handling file uploads in a web application. It provides convenient
methods for getting the file's information and content.
Use byte[] if you need to store or process binary data. It's a compact and efficient way to
represent bytes.
Use InputStream if you need to read data from a file or network connection. It's a flexible
and versatile way to access data. A stream also has the advantage that you don't have to
have all bytes in memory at the same time, which is convenient if the size of the data is large
and can easily be handled in small chunks.
When a class implements the Serializable interface, all its sub-classes are serializable as well.
However, when an object has a reference to another object, these objects must implement the
Serializable interface separately, or else a NotSerializableException will be thrown
assertTrue(matcher.find());
Sort employee with age and salary? Write comparable and Comparator
Comparable
@Override
Comparator
emps.sort(Comparator.comparing(Emp::getAge).thenComparing(Emp::getSalary));
https://stackoverflow.com/questions/47688418/what-is-the-difference-between-intermediate-and-
terminal-operations
https://stackoverflow.com/questions/1539793/in-java-does-anyone-use-short-or-byte
https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil
https://medium.com/att-israel/should-you-avoid-using-static-ae4b58ca1de5
Custom exception
Here are some examples of when you might want to create a custom exception:
You have a specific business rule that needs to be enforced. For example, you might want to
create an exception if a user tries to enter a negative number into a field.
You want to provide more specific error messages to users. For example, you might want to
create an exception that tells the user that they entered an invalid email address.
You want to improve the readability of your code. For example, you might want to create a
custom exception for all exceptions that occur in a particular class.
You want to handle exceptions in a custom way. For example, you might want to log all
exceptions that occur in your application.
https://stackoverflow.com/questions/22698584/when-should-we-create-our-own-java-exception-
classes
Stream peek
It is used to print the elements of stream. But peek is an intermediate operation unlike forEach
which is a terminal operation.
IntStream to ArrayList
Intstream needs to be boxed to collect to list
Finally
Yes, a finally block always executes, even if an exception is thrown and there is no catch block to
handle it. Finally is called even if try block has a return statement. Even if there is a return statement
in try and catch return value of finally will be the value returned. Finally does not execute when
System.exit(0) is called.
readResolve()
The readResolve method in Java allows a class to replace or resolve an object read from a stream
before it is returned to the caller. It is called when the ObjectInputStream has read an object from
the stream and is preparing to return it to the caller.
The readResolve method is typically used to implement the Singleton pattern, where the same
object needs to be returned after deserialization. It is also used to set the values of the object's non-
transient fields that were not serialized
Object.clone
The Object.clone() method in Java creates a shallow copy of an object. This means that the cloned
object will have the same field values as the original object, but it will reference the same objects as
the original object. If you modify a field in the cloned object, the change will be reflected in the
original object.
https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java
https://www.codejava.net/java-core/collections/generics-with-extends-and-super-wildcards-and-
the-get-and-put-principle
Inner Class
https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class
https://www.javatpoint.com/member-inner-class
https://www.javatpoint.com/anonymous-inner-class
https://www.javatpoint.com/local-inner-class
https://www.javatpoint.com/static-nested-class
https://www.javatpoint.com/nested-interface
AIC can use instance variables and thus can have state, lambdas cannot.
https://www.baeldung.com/java-lambdas-vs-anonymous-class
https://medium.com/@nagarjun_nagesh/lambda-functions-vs-anonymous-inner-classes-in-java-
80893c2214d5
Record