The copy constructor is use for initialising a new instance from an old instance,
JVM Architecture | 1. Bootstrap ClassLoader loads classes from the location rt.Jar2. Extension ClassLoader loads files from jre/lib/ext directory or any other directory pointed by the system property java.Ext.Dirs 3. System ClassLoader loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option |
|---|---|
1. Method Area is a part of the heap memory which is shared among all the threads. It is used to store class structure, superclass name, interface name, and constructors.2. Heap stores the actual objects, When you use a new keyword While the reference of that object stores in the stack, it also stores Objects, String literals, instance variables and methods.3. Stack Area generates when a thread creates.It contains references to heap objects.It also stores Local variables, reference variables. Stack memory is stored in computer RAM, similar to the heap.4. PermGen/Metaspace Sotres class structure, static variables, static methods, static blocksPermGen | |
1. Objects are created on the heap, Some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.2. There are generally 4 ways to make an object eligible for gc. It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort. |
| Aggregation | Composition | Association |
|---|---|---|
| Aggregation is a weak Association. | Composition is a strong Association. | Weakest relationship among all. |
| Class can exist independently without owner. | Class can not meaningfully exist without owner. | |
| Have their own Life Time. A uses B. | Life Time depends on the Owner. A owns B. | |
| Child is not owned by 1 owner. | Child can have only 1 owner. | |
| Has-A relationship. A has B. Denoted by a empty diamond in UML. | PartOf relationship. B is part of A.Denoted by a filled diamond in UML. | |
| We do not use “final” keyword for Aggregation. | “final” keyword is used to represent Composition. | |
| It represents the Has-A relationship. | It represents a part-of-relationship. | |
| It is a unidirectional association i.E. A one-way relationship. For example, the department can have students but vice versa is not possible and thus unidirectional in nature. | In composition, both entities are dependent on each other. | |
| In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity. | When there is a composition between two entities, the composed object cannot exist without the other entity. For example, if order HAS-A line-items, then an order is a whole, and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted. Favor Composition over Inheritance. | Let’s take an example of a Teacher and Student. A single student can be associated with multiple teachers, and a single teacher can teach multiple students, but both have their own lifecycles (both can be created and deleted independently) |
| Relationship between two classes such that objects of both classes can have independent lifecycle, but object of one class will belong to a specific object of the another class in its lifetime. It cannot belong to two objects of the same class. | It to refer to relationships where two objects don’t have an independent lifecycle, and if the parent object is deleted, all child objects will also be deleted. | Association is not a has-a relationship and the weakest relationship among all. In an Association relationship, none of the objects are parts or members of another. A simple example of Association is a mother and her child. |
Examples: – A Human uses Clothes. ~ Mobile has a SIM Card. | Examples: – A Human owns the Heart. – A Company is a composition of Accounts. ~ IMEI Number is a part of a Mobile. | Relationships/Association One-to-One One-to-Many Many-to-One Many-to-Many |
| Method Overloading | Method Overriding |
|---|---|
| Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
| Method overloading is performed within class. | Method overriding occurs in two classes that have IS-A (inheritance) relationship. |
| Both methods must have different argument lists. | It must have the same arguments. |
| Both methods must have the same method name. | It must have the same method name. |
| Method overloading is the example of compile time polymorphism. | Method overriding is the example of run time polymorphism. |
| Can’t be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameters or order of parameters | It must have the same return type. From Java 5 onward, the return type can also be a subclass (subclasses are a covariant type to their parents). |
| It can have different access modifiers. | It must not have a more restrictive access modifier (if parent → protected then child → private is not allowed). |
| It can Throw different checked or unchecked exceptions. | It must not throw new or broader checked exceptions. |
Apart from the above rules, there are also some facts to keep in mind:
Only inherited methods can be overridden. That means methods can be overridden only in child classes
Constructors and private methods are not inherited, so they cannot be overridden
Abstract methods must be overridden by the first concrete (non-abstract) subclass
Final methods cannot be overridden
A subclass can use super.Overridden_method() to call the superclass version of an overridden method
String Cheat Sheet
1. What is the difference between equals() method and == operator?
The equals() method matches content of the strings whereas == operator matches object or reference of the strings.
2.Java String intern()
It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.
3. Explain String pool in Java
String Pool, also known as SCP (String Constant Pool), is a special storage space in Java heap memory that is used to store unique string objects. Whenever a string object is created, it first checks whether the String object with the same string value is already present in the String pool or not, and if it is available, then the reference to the string object from the string pool is returned. Otherwise, the new string object is added to the string pool, and the respective reference will be returned.
4. Is String immutable or final in Java? If so, then what are the benefits of Strings being Immutable?
Yes, Strings are immutable in Java. Immutable objects mean they can’t be changed or altered once they’ve been created. However, we can only modify the reference to the string object. The String is immutable in Java because of many reasons like security, caching, synchronization and concurrency, and class loading.
5. Is String thread-safe in Java?
Strings are immutable objects, which means they can’t be changed or altered once they’ve been created. As a result, whenever we manipulate a String object, it creates a new String rather than modifying the original string object. In Java, every immutable object is thread-safe, which means String is also thread-safe. As a result, multiple threads can access a string. For instance, if a thread modifies the value of a string, instead of modifying the existing one, a new String is created, and therefore, the original string object that was shared among the threads remains unchanged.
6. Why is a string used as a HashMap key in Java?
Basically, the HashMap object can store key-value pairs. When creating a HashMap object and storing a key-value pair in that object, you will notice that while storing, the hash code of the key will be calculated, and its calculated value will be placed as the resultant hash code of the key. Now, when the key is passed to fetch its value, then the hash code of the key is calculated again, and if it’s equal to the value of the hash code initially calculated, the initial value placed as the resultant hash code of the key is retrieved or fetched.
7. How to create Immutable class in Java?
- Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
- The class must be declared as final so that child classes can’t be created.
- Data members in the class must be declared private so that direct access is not allowed.
- Data members in the class must be declared as final so that we can’t change the value of it after object creation.
- A parameterized constructor should initialize all the fields performing a deep copy so that data members can’t be modified with an object reference.
- Deep Copy of objects should be performed in the getter methods to return a copy rather than returning the actual object reference)
Note
There should be no setters or in simpler terms, there should be no option to change the value of the instance variable.
8. Object Cloning in Java
The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.
The java.Lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement
Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
Student18 s1=new Student18(101,”amit”);
Student18 s2=(Student18)s1.Clone();
| Key | final | finally | finalize |
|---|---|---|---|
| Definition | final is the keyword and access modifier which is used to apply restrictions on a class, method or variable. | finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. | finalize is the method in Java which is used to perform clean up processing just before object is garbage collected. |
| Applicable to | Final keyword is used with the classes, methods and variables. | Finally block is always related to the try and catch block in exception handling. | finalize() method is used with the objects. |
| Functionality | (1) Once declared, final variable becomes constant and cannot be modified. (2) final method cannot be overridden by sub class. (3) final class cannot be inherited. | (1) finally block runs the important code even if exception occurs or not. (2) finally block cleans up all the resources used in try block | finalize method performs the cleaning activities with respect to the object before its destruction. |
| Execution | Final method is executed only when we call it. | Finally block is executed as soon as the try-catch block is executed. It’s execution is not dependant on the exception. | finalize method is executed just before the object is destroyed. Using System.Gc() or gc auto called |
Making a class final means that it won’t be possible to extend that class Adding final to a method means that it won’t be possible to override that method Finally, putting final in front of a field, a variable or a parameter means that once the reference has been assigned then it cannot be changed (however, if the reference is to a mutable object, it’s internal state could change despite being final) | The finally block is an optional block to use with a try/catch statement. In this block, we include code to execute after the try/catch structure, whether an exception is thrown or not. | And finally, the finalize method is a protected method, defined in the Object class. It’s called by the garbage collector on objects that aren’t referenced anymore and have been selected for garbage collection. |
Differences between final and immutability
- final means that you can’t change the object’s reference to point to another reference or another object, but you can still mutate its state (using setter methods e.G). Whereas immutable means that the object’s actual value can’t be changed, but you can change its reference to another one.
- final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables.
- By declaring a reference variable as final, we won’t get any immutability nature, Even though reference variable is final. We can perform any type of change in the corresponding Object. But we can’t perform reassignment for that variable.
- final ensures that the address of the object remains the same whereas the Immutable suggests that we can’t change the state of the object once created.
Singleton Method Design Pattern in Java
1. Ensure that only one instance of the class exists2. Provide global access to that instance by
There are two forms of singleton design patterns, which are:
| class Singleton { // Declaring a variable of type String PublicString s; // Constructor Here we will be creating private constructor restricted to this class itself // Static method to create instance of Singleton class return single_instance; |
Serialization and Deserialization in Java
1. Java Serialization is a mechanism by which Java objects can be converted into a byte stream, and consequently, can be reverted back into a copy of the object. 4. For each object, the non-static and non-transient fields are included in the serialized representation5. If any field is an object that also implements Serializable, the process is recursively applied to that object6. The writeObject method may be implemented for custom serialization of an object7. Assigning SerialVersionUID: A serialVersionUID is computed if it’s not specified. This ID must match during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. 8. Handling transient and static Fields: Fields declared as transient or static are ignored by the serialization process, as transient fields are not part of the persistent state of the object, and static fields are part of the class state, not the individual object state. 9. For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class. | Serialization :Student s1 =new Student(211,”ravi”); Deserialization: ObjectInputStream in=new ObjectInputStream(new FileInputStream(“f.Txt”)); Student s=(Student)in.ReadObject(); //printing the data of the serialized object System.Out.Println(s.Id+” “+s.Name); //closing the stream in.Close(); |
Parameters
Interface
Abstract class
Speed
Slow
Fast
Multiple Inheritances
Implement several Interfaces
Only one abstract class
Structure
Abstract methods
Abstract & concrete methods
When to use
Future enhancement
To avoid independence
Inheritance/ Implementation
A Class can implement multiple interfaces
The class can inherit only one Abstract Class
Default Implementation
While adding new stuff to the interface, it is a nightmare to find all the implementors and implement newly defined stuff.
In case of Abstract Class, you can take advantage of the default implementation
Access Modifiers
The interface does not have access modifiers. Everything defined inside the interface is assumed public modifier
Abstract Class can have an access modifier
When to use
It is better to use interface when various implementations share only method signature. Polymorphic hierarchy of value types.
It should be used when various implementations of the same kind share a common behavior
Data fields
the interface cannot contain data fields.
The class can have data fields
Multiple Inheritance Default
A class may implement numerous interfaces
A class inherits only one abstract class
Implementation
An interface is abstract so that it can’t provide any code
An abstract class can give complete, default code which should be overridden
Use of Access modifiers
You cannot use access modifiers for the method, properties, etc
You can use an abstract class which contains access modifiers
Usage
Interfaces help to define the peripheral abilities of a class
An abstract class defines the identity of a class
Defined fields
No fields can be defined
An abstract class allows you to define both fields and constants
Inheritance
An interface can inherit multiple interfaces but cannot inherit a class
An abstract class can inherit a class and multiple interfaces
Constructor or destructors
An interface cannot declare constructors or destructors
An abstract class can declare constructors and destructors
Limit of Extensions
It can extend any number of interfaces
It can extend only one class or one abstract class at a time
Abstract keyword
In an abstract interface keyword, is optional for declaring a method as an abstract
In an abstract class, the abstract keyword is compulsory for declaring a method as an abstract
Class type
An interface can have only public abstract methods
An abstract class has protected and public abstract methods
Comparator Vs Comparable In Java
Comparison Basis
Comparable
Comparator
Method
Comparable provides compareTo() method to sort elements in Java
Comparator provides compare() method to sort elements in Java
Package
A comparable interface is present in java.Lang package
A comparator interface is present in java.Util package
Logic of Sorting
The logic of sorting must be in the same class as the object you are going to sort
The logic of sorting should be in separate classes to write different sorts based on different attributes of objects.
Class Object
The class whose objects you want to sort must implement the Comparable interface
A class whose objects you want to sort does not need to implement a comparator interface
Sorting Sequences
It provides single sorting sequences
It provides multiple sorting sequences
Sorting Order
This method can sort the data according to the natural sorting order
This method sorts the data according to the customized sorting order
Class
It affects the original class. I.E., the actual class is altered
It doesn’t affect the original class, i.E., the actual class is not altered
Usage
Implemented frequently in the API by Calendar, Wrapper classes, Date, and String
It is implemented to sort instances of third-party classes
Implement
All wrapper classes and string classes implement comparable interfaces
The only implemented classes of Comparator are Collator and RuleBasedColator
publicclass
Comparingimplements
Comparable<Comparing> {
privateint x;
private String y;
@Override
publicintcompareTo(Comparing o)
{
if(this
.GetX() == o.GetX()){
returnthis
.GetY().CompareTo(o.GetY());
}
else {
returnthis
.GetX() > o.GetX() ? 1 : –1 ;
}
}
}Comparing comparing1 = new
Comparing(1,“a”)
;
Comparing comparing2 = new
Comparing(2,“c”)
;
Comparing comparing3 = new
Comparing(4,“b”)
;
List<Comparing> list = new
ArrayList<>();
list.Add(comparing1);
list.Add(comparing2);
list.Add(comparing3);
Collections.Sort(list);
publicclass
ComparingComparable {
@Override
publicintcompare(Comparing car1, Comparing car2)
{
if (car1.Fuel == car2.Fuel) return 0; return car1.Fuel < car2.Fuel ? -1 : 1;
}
Comparingcomparing1=newComparing(1,“a”
);
Comparingcomparing2=new
Comparing(2,“c”
);
Comparingcomparing3=new
Comparing(3,“b”
);
List<Comparing> list = new
ArrayList<>();
list.Add(comparing1);
list.Add(comparing2);
list.Add(comparing3);
Collections.Sort(list,Comparator.
comparing(Comparing::getX));
Collections.Sort(list,Comparator.Comparing(Comparing::getY));
