CoreJava

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

JDK vs JRE vs JVM

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 (part-of) vs aggregation (has-a)


Aggregation is a relatively weak association, whereas Composition is a strong association.

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.

Why Java is platform independent and JVM platform dependent


Java source code is compiled into bytecode, which is a platform-independent intermediate
representation of the program. The bytecode can then be executed on any platform that has a JVM
for that platform. JVM is platform-dependent because it needs to be able to interact with the
underlying operating system and hardware. This means that there is a different JVM for each
platform, such as Windows, macOS, and Linux.

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.

Java features by version


https://www.baeldung.com/java-8-new-features

Modifying while iterating on stream will throw concurrent mod exp?


Yes, it will throw for HashMap when forEach is used instead of collect.

But ConcurrentHashMap doesn't throw a ConcurrentModificationException if the underlying


collection is modified during an iteration.

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.

Why iterator.remove does not throw ConcurrentModificationException


https://stackoverflow.com/questions/24856811/why-iterator-remove-does-not-throw-
concurrentmodificationexception

Iterator throws ConcurrentModificationException when list data is modified after


creating iterator

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.

Abstract class vs interface


If state is needed and multiple inheritance is not required then abstract class should be used

Overriding default method in interface


Yes, you can override a default method in an interface. You can override default methods like you
would normal methods of a superclass. However, you must remove the default keyword before the
method.

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.

Diamond problem solution in java with default methods in interface


https://stackoverflow.com/questions/51989335/solving-the-java-interface-diamond-issue

Why only functional interface is supported in lambda?


Java supports lambda expressions only with functional interfaces because functions are based on
objects. A lambda expression is an anonymous class that implements the functional interface's
abstract method.

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.

Overloading & Overriding


To overload a method, type or number of arguments must differ. Overloaded method can have
different return type.

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

Override static method – Method Hiding


It is not possible to override a static method in Java. This is because static methods are bound to the
class and not associated with an object. They cannot be overridden because they do not act on a
specific instance of an object.

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.

Overriding Instance Variable – Variable hiding


Variable hiding in Java happens when there is a variable declared in a child class with the same name
as the variable declared in the parent class. The child class's variable hides the parent class's
variable, even if their types are different.

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:

Dog dog = new Dog();

String name = dog.super.name;

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

Stream with char


mapToObj should be used to convert a str.chars() to convert the intstream to char. And char cannot
be cast to string.

Stream performance – Lazy evaluation in stream


In Java, streams are called lazy evaluation because intermediate operations are not executed until a
terminal operation is invoked. This means that the computation on the elements of the stream is
only performed when it's necessary, usually at the point of the terminal operation.

For example, consider the following code:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Stream<Integer> stream = numbers.stream();

// The intermediate operation filter is not executed until the terminal operation is called

stream.filter(n -> n % 2 == 0).forEach(System.out::println);

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.

Streams can also process in parallel.


Checked vs unchecked exception
Checked exceptions should be used when the error is due to a programming fault or a faulty input.
Unchecked exceptions should be used when the error is due to a condition that the programmer
cannot control, such as a networking issue.

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.

Checked Exception: IOException, SQLException and ParseException

Unchecked Exception: NullPointer, Arithmetic

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.

Here are some examples of errors in Java:

 OutOfMemoryError
 StackOverflowError:
 NoClassDefFoundError: This error occurs when the program tries to load a class that cannot
be found.

Here are some examples of exceptions in Java:

 ArithmeticException
 ArrayIndexOutOfBoundsException:
 FileNotFoundException

Exception in overridden method


If parent method throws nullpointer then the overridden child method cannot throw exception of
type “Exception” it can throw only null pointer or children of null pointers

Hashcode and equal method contract


equals() Contract

 reflexive: an object must equal itself


 symmetric: x.equals(y) must return the same result as y.equals(x)
 transitive: if x.equals(y) and y.equals(z), then also x.equals(z)
 consistent: the value of .equals() should change only if a property that is contained
in .equals() changes (no randomness allowed)

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/

Importance of hashcode and equal in map and set


 Override only equals – will result in duplicate values in different bucket as hashcode will be
different
 Override only hashCode – will result in duplicate values in same bucket as equal will be
different

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.

Null key lands in which bucker in hashmap


If the key that we are inserting is null, then it is inserted at index 0 because the hashcode of null is 0.
If the key is not null, then the hash of the key is calculated, and based on the hash value the bucket
is decided

Custom object as key in hashmap


 Unique key
 Immutable
 Override hashcode and equal
https://www.baeldung.com/java-custom-class-map-key
https://stackoverflow.com/questions/45831828/can-we-use-object-as-a-key-in-hashmap-in-java

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.

getClass() == ... tests whether the types are identical.

Hashcode implementation
https://www.baeldung.com/java-hashcode

https://stackoverflow.com/questions/16629893/good-hashcode-implementation

Multipart vs bytearray vs input stream?


MultipartFile is a Spring-specific class that represents a file upload. It provides methods to get the
file's name, size, content type, and byte array. MultipartFile is typically used when handling file
uploads in a web application.

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.

Serialization and deserialization


https://www.scaler.com/topics/java/serialization-and-deserialization/

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

Serial Version UID


If serialVersionUID is not provided in a Serializable class, the JVM will generate one automatically.
However, it is good practice to provide the serialVersionUID value and update it after changes to the
class so that we can have control over the serialization/deserialization process.
https://www.baeldung.com/java-serial-version-uid#:~:text=If%20serialVersionUID%20is%20not
%20provided,over%20the%20serialization%2Fdeserialization%20process.

Check if provided string is a number


Character.isDigit or parseInt or regEx

Pattern pattern = Pattern.compile("foo");

Matcher matcher = pattern.matcher("foo");

assertTrue(matcher.find());

Sort employee with age and salary? Write comparable and Comparator
Comparable

@Override

public int compareTo(Emp o) {

return Comparator.comparing(Emp::getAge).thenComparing(Emp::getSalary).compare(this, o);

Comparator

emps.sort(Comparator.comparing(Emp::getAge).thenComparing(Emp::getSalary));

Stream -> terminal operations and intermediate operations


https://stackoverflow.com/questions/52926280/what-does-it-mean-intermediate-operations-are-
lazily-executed-whereas-terminal-o

https://stackoverflow.com/questions/47688418/what-is-the-difference-between-intermediate-and-
terminal-operations

Interface based programming


https://stackoverflow.com/questions/1992384/program-to-an-interface-what-does-it-mean

+ concatenation use string builder


https://stackoverflow.com/questions/25492475/when-is-the-operator-faster-than-a-stringbuilder

Why string is immutable ?


https://stackoverflow.com/questions/22397861/why-is-string-immutable-in-java#:~:text=IMHO%2C
%20this%20is%20the%20most,would%20affect%20all%20another%20client.
Casting
https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-
down-casting-with-respect-to-class#:~:text=upcasting%20means%20casting%20the
%20object,necessary%20as%20it's%20done%20automatically.

Short and Byte


https://stackoverflow.com/questions/27122610/why-does-the-java-api-use-int-instead-of-short-or-
byte

https://stackoverflow.com/questions/1539793/in-java-does-anyone-use-short-or-byte

Float and double


https://stackoverflow.com/questions/27598078/float-and-double-datatype-in-java

Static method in design


https://medium.com/@karmanno/why-are-static-embers-and-methods-bad-for-object-oriented-
design-b4d0c141512c#:~:text=The%20messaging%20principle%20seems%20to,a%20Java%20static
%20method%20Foo.

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

Hashmap load factor


https://www.baeldung.com/java-hashmap-load-factor#:~:text=The%20load%20factor%20is
%20the,code%20of%20already%20stored%20entries.
Lambda Exception Handling
https://www.baeldung.com/java-lambda-exceptions

Stream side effects

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

Arrays.stream(arr).boxed().filter(num -> num<0).collect(Collectors.toList());

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.

Generics wild card


 Use an extends wildcard when you only get values out of a structure.
 Use a super wildcard when you only put values into a structure.
 And don’t use a wildcard when you both get and put.

And there are two exceptions:


 You cannot put anything into a type declared with an extends wildcard except for the value
null, which belongs to every reference type.
 You cannot get anything out from a type declared with a super wildcard except for a value of
type Object, which is a super type of every reference type.

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

Why List<Child> not a subtype of List<Parent>


https://stackoverflow.com/questions/1240316/why-is-listnumber-not-a-sub-type-of-listobject

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

Byte casting to int


Char casting to int and string
Flux?
Functional vs Object Oriented vs reactive programming
Reactive vs Event Driven
Reactive vs Asynchronous
String intern
Singleton vs static
Super and this in constructor

This keyword in lambda expression


this keyword in a lambda expression refers to the this parameter of a method where the lambda
expression is located. The this keyword in a lambda expression is the same as in the enclosing
context.

And this keyword cannot be used within static method.


Compose andThen
Both these methods allow us to compose multiple functions into a single function but offer different
semantics. While compose applies the function passed in the argument first and then the function
on which it's invoked, andThen does the same in reverse.

x.andThen(y) is the same as y.compose(x).

anonymous inner class vs lambda expression


An anonymous inner class is more powerful as we can use many methods as we want, whereas
lambda expression can only be used where an interface has only a single abstract method.

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

You might also like