What is mutable object and immutable object?
If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
Eg. public class Test138
{
public static void stringReplace (String text)
{
text = text.replace ('j' , 'c'); /* Line 5 */
}
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c"); /* Line 9 */
}
public static void main (String args[])
{
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */
stringReplace(textString);
bufferReplace(textBuffer);
System.out.println (textString + textBuffer);
}
}
Ans. Javajavac (since string cannot be replaced java remains as java only)
Note: String is immutable means we cannot change the value of the object by passing it in a method.
Also,
String a="123"; is same as
String a= new String("123");
Example 2:
String str = "knowledge";
String s = str; // assigns a new reference to the same string "knowledge"
str.concat(" base");
System.out.println("str: "+str);
System.out.println("s: "+s);
str = str.concat(" base"); //changing value of reference variable
System.out.println("str1: "+str);
Output:
str: knowledge
s: knowledge
str1: knowledge base
Note: knowledge object is not modified. It still exist.
Suppose there are 5 reference variables,all referes to one object "knowledge".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
How to make a class immutable
Declare the class as final.
Object Oriented vs Object Based programming language
Object Oriented: Supports all object oriented features like inheritance, polymorphism, encapsulation, data hiding and abstraction.
Object Based: Does not support inheritance and polymorphism.
JavaScript and VBScript are examples of object based programming languages.
How to call Parent class method without creating object
By calling super ie. super.methodname()
eg.
class A
public class A {
public void methodA()
{
System.out.println("class A");
}
}
class B
public class B extends A
{
public void methodA()
{
super.methodA();
System.out.println("class B");
}
}
class C
public class C {
public static void main(String args[])
{
B b=new B();
b.methodA();
}
}
Output:
class A
class B
Super() vs super
1)super() is used to invoke parent class constructor.
2)super is used to invoke parent class method or instance variable
eg. super.methodName()
super.speed // here speed is of data type int
Object class:
At any point of time in your class hierarchy you will always have Object at the top level.
Every class is a descendant, direct or indirect, of the Object class.
class A
class B extends A
Here class A implicitly extends Object but class B does not extend class Object directly
Will following program compile & execute ?
class A
{
private static main(String args[])
{
System.out.println("Hello Java");
}
}
Ans:
Method main( ) can be specified as private or protected and it will compile but it will not run
ClassNotFoundException vs NoClassDefFoundError
ClassNotFoundException is a checked Exception while NoClassDefFoundError is an Error
Example :
public class Test1
{
}
public class Test
{
public static void main(String[] args)
{
Test1 = new Test1();
}
}
Now after compiling both the classes , if you delete Test1.class file , and run Test class , it will throw Exception in thread "main" java.lang.NoClassDefFoundError: Test
StringBuilder vs StringBuffer in Java
StringBuffer is synchronized, StringBuilder is not.
StringBuilder is faster than StringBuffer because it's not synchronized
StringBuilder (introduced in Java 5) is identical to StringBuffer
Note: We can't synchronize a class. We can only synchronize methods and block. Then how StringBuffer class is synchronized? Answer is all the methods of StringBuffer class is synchronized so we say StringBuffer class is synchronized.
HttpServlet vs GenericServlet
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
GenericServlet class can handle any type of request so it is protocol-independent.
HttpServletRequest interface
The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc). So we do not create object of it.
What is use of load-on-startup in web.xml ?
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.example.SecondServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
It loads the servlet at the time of deployment. Hence it would be faster when the first request for servlet comes in, otherwise a servlet is loaded only when the first request comes.
Note:
Passing positive value:
The 0 value will be loaded first then 1, 2, 3 and so on.
If two or more servlets have the same <load-on-startup> positive integer value then they will be loaded in an order on which they are declared inside web.xml file.
Passing negative value:
If you pass the negative value, servlet will be loaded at request time, at first request.
Runtime Polymorphism (upcasting):
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass(upcasting). The determination of the method to be called is based on the object being referred to by the reference variable.
Upcasting:
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
class A{}
class B extends A{}
A a=new B();//upcasting
Method overloading vs Method overriding
Method overloading is performed within class while Method overriding occurs in two classes.
In case of method overloading, parameter must be different while In case of method overriding, parameter must be same.
Eg. method 0verloading (Compile tile Polymorphism):
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
static String add(String a,String b){return a+b;}
Eg. method 0verridding (Runtime Polymorphism):
class A{
void run()
{System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run()
{System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
Restrictions for static method
There are two main restrictions for the static method. They are:
1.The static method cannot use non static data member or call non-static method directly.
2.this and super cannot be used in static context.
Note: anyone can access static, but static cannot access everyone.
Example: class A{ int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Output: Compile Time Error
Can we execute a program without main() method?
Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
Example:
class StaticBlock{
public static void main(String args[]){
System.out.println("main");
}
static
{
System.out.println("static block is always executed first even before main method");
}
}
Output:
static block is always executed first even before main method
main
What’s the difference between constructors and normal methods?
Constructors must have the same name as the class and cannot return a value.
They are only called once and constructors cannot be inherited.
Constructors are used to initialize objects while regular methods could be called many times and it can return a value or can be void.
Constructors have one purpose in life: to create an instance of a class. This can also be called creating an object.
A method's basic function is to execute Java code.
Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract, final, native, static, or synchronized.
Example of default constructor
Bike b=new Bike();
Example of parameterized constructor
Student s1 = new Student(111,"Rahul");
Student s2 = new Student(222,"Aryan");
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.
Can constructors be synchronized in Java?
No, constructors can take only access modifiers. Also because only the thread that creates an object should have access to it and also constructor can be called only once
Can we declare a constructor final?
No, because constructor is never inherited
Can we call constructor from a method?
No, Because constructor should be the first statement.
Note: Even if constructor is not written in 1st statement in a class it is always called 1st, but we cannot call constructor from a method.
Can we call method from a constructor?
Yes
Arguments vs Parameters
int sum(int addend1, int addend2)
{
return addend1 + addend2;
}
The function sum has two parameters, named addend1 and addend2
int sumValue;
int value1 = 40;
int value2 = 2;
sumValue = sum(value1, value2);
The variables value1 and value2 are initialized with values. value1 and value2 are both arguments to the sum function
compareTo() vs equals() vs == operator :
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. While equals returns true or false. == operator compares reference(address)and returns true or false
compareTo():
class Simple{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output: 0
1
-1
equals() and == operator :
String s1="Sachin";
String s2="Sachin";
String s3=new String(“Sachin”);
System.out.println(s1.equals(s2)); //compares value of variable
System.out.println(s1.equals(s3));
System.out.println(s1==s2);
System.out.println(s1==s3);//compares value of address location
Output: True
True
True
False
How to count active sessions in your web application?
By implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.
Collections:
A collections is a single object managing a group of objects. The objects in the collection are called elements.
Set : An unordered collection; no duplicates are permitted
List : An ordered collection; duplicates are permitted
Generics: (Collections vs Generics)
Generics are same as Collections but the difference is that
1] Collections are heterogeneous(accepts INTEGER,FLOAT etc) but Generics accept only one type(homogeneous).
2] Type casting is required for Collections for retrieval.
eg.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
list.add(new Integer(4));
String s = (String) list.get(0);//typecasting
Integer i = (Integer) list.get(1);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
hashCode() or how does HashTable/HashMap/HashSet work:
The hash code only points to a certain area (or list, bucket etc). The HashTable then iterates this area and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.
The hashCode() method is used when you insert objects into a HashTable, HashMap or HashSet.
Hashset
The hashset class is used to create a collection and store it in a Hashtable. Each collection refers to a unique value called hash code. This type of sorting information in a hashtable is called hashing.
HashTable
HashTable is used to store value in the form of map key with value. The key should implement the hashcode and equals method to store and retrieve values in a HashTable
Hashmap vs hashtable vs LinkedHashMap
1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
2. HashTable does not allow null keys or values. HashMap allows one null key and any number of null values.
3. One of HashMap's subclasses is LinkedHashMap
3.1)HashMap doesn't maintain any order while LinkedHashMap maintains insertion order of elements in Java.
3.2) LinkedHashMap also requires more memory than HashMap because of this ordering feature.
3.3) LinkedHashMap actually extends HashMap and implements Map interface(rest of the features are same as HashMap as it extends it)
HashSet vs LinkedHashSet
1)HashSet does not maintain any order while LinkedHashSet maintains insertion order
2)HashSet is faster than LinkedHashSet
3)Both HashSet and LinkedHashSet allows null
What is difference between HashSet and HashMap?
HashSet contains only values whereas HashMap contains entry(key,value).
What is difference between HashSet and TreeSet?
HashSet maintains no order whereas TreeSet maintains ascending order.
What is difference between HashMap and TreeMap?
1) HashMap can contain one null key. TreeMap cannot contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.
Note:
Vector and HashTable is synchronized. Remaining classes can be synchronized as follows:
List:
List li = new ArrayList()
Collections.synchronizedList(li)
Set:
Collections.synchronizedSet(set);
Map:
Collections.synchronizedMap(map);
Convert ArraylList to array
.toArray is used to convert ArraylList to array
eg.
Integer list2[] = new Integer[arrlist.size()]; //initialize array
list2 = arrlist.toArray(list2);
Convert array to ArraylList
Arrays.asList(al) is used to convert array to ArraylList
Convert Map to Json
Gson gson = new Gson();
String json = gson.toJson(myObject);
length() vs length vs size()
.length() is a method of String
.length is an attribute of an array(used in array only)
.size() provides the number of object actually stored in collection(used in collection only)
Concurrent Collections:
-Concurrent Collections allows multiple threads to access different parts of a collection at a given time.
-java.util.concurrent.
Interfaces:
1)BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.
2)ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent.
Making these operations atomic helps avoid synchronization.
-ConcurrentHashMap does not allow null keys or values.
Click to Zoom |
fail-fast Iterator :
-It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. If it does then the results of the iteration are undefined under these circumstances.
-Some Iterator implementations may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators.
- They fail quickly and cleanly, rather that risking arbitrary.
fail-safe Iterator:
fail-safe iterator doesn't throw any Exception because Fail Safe Iterator makes copy of the internal data structure and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure. So , original data structure remains structurally unchanged.
Array vs Arraylist
Arrays:
1)Fixed size once created
2)Can contain objects and primitives
egFish[] myArray = new Fish[15];
3)Stores similar data of one type.
4)It is not a class
5)Cannot be synchronized
6)Uses for loop
ArrayLists:
1)Dynamic size,grows automatically
2)Can only contain objects.
eg.ArrayList myList = new ArrayList();
3)Can store heterogeneous data types.
4)It is a class
5)Can be synchronized
6)Uses for loop and iterators
Arraylist vs LinkedList
Search:
ArrayList is faster than LinkedList in searching nth element as it is index based. LinkedList has to traverse the list from the beginning to get to the n-th element.
Insert and delete:
Insertions and deletions are fast in LinkedList as compared to ArrayList. ArrayList's slower since the internal backing-up array needs to be reallocated. ArrayList also needs to be update its index.
Can we have static class?
Yes inside inner class.
It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Example:
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Can we have a private or protected class?
No.
Only public abstract and final are allowed.
It will not compile if private or protected is used.
Static class loading vs Dynamic class loading:
Static class loading:
Classes are statically loaded by using Java’s new operator.
Dynamic class loading(Reflection):
-Dynamic loading is invoking the function of a class loader at runtime(Reflection).
-It is useful when the name of the class is not known at compile time.
-This is done with the help of the following methods:
getClass(); getName(); etc.
Example:
Object o = new MyClass();
System.out.println(o.getClass().getName());
-The getClass() method gets the actual class, of the object
-The getName() method will return the full package plus class name of that class as a string, like this:
com.company.MyClass
-A ClassNotFoundException is thrown if no definition is found.
Reflection:
Reflection is commonly used to modify the runtime behavior of applications.
What is Marker interfaces in Java?
Marker interface in Java is interfaces with no field or methods.
If it is empty interface then what is the use of it?
Marker interface in Java is used to indicate something to compiler.It is metadata about a class.
In modern Java, marker interfaces have no place. They can be completely replaced by Annotations.
Annotations:
Annotations are used to provide META data to the classes.
Every annotations is internally an Interface.
The annotations applied on java sourcecode is compiled into bytecode
Example 1:
// Declares the annotation DemoAnnotation without any value
public @interface DemoAnnotation {
}
//Use the annotation like below
@DemoAnnotation
public void toggle() {
}
Example 2:
public @interface Author {
String first();
String last();
}
//Use the annotation like below
@Author(first = "abc", last = "xyz")
Book book = new Book();
clone():
The clone( ) method generates a duplicate copy of the object.
Only classes that implement the Cloneable interface can be cloned.
Cloneable interface is marker interface.
Why use clone() method ?
The clone() method saves the extra processing task.
What is Thread safe in java ?
Thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurring.
If a class/method is not thread safe we can make it thread safe by using synchronized keyword.
JVM guarantees that synchronized code will be executed by only one thread at a time.
Eg. synchronized void call()
{
// ……
}
The way of doing this in JSP is
<%@page isThreadSafe="false" %> (default value is true)
Race condition:
-When two or more threads access shared data(object) at the same time and they try to change it is known as race condition.
-It can be avoided by using synchronized keyword.
-Synchronization is done with the help of locks.
-Threads gain access to shared object by first acquiring lock associated with it. So other threads are prevented from acquiring the lock of the same object.
-Note that if one thread enters synchronized method no other thread can enter any other synchronized method of same object.
Disadvantages of synchronized method:
-Greater chances of deadlock.
-This kind of deadlock can be avoided by synchronized block.
-Scope of synchronized block is smaller than the method.
-Synchronized block is useful if code has been developed by 3rd party and you cannot add synchronize to a method. So you can call that method in synchronized block.
-In synchronized block thread acquires lock of random object.
eg.
private static Object sharedLock = new Object(); // Any object's instance(random) can be used as a lock.
public int getX() {
synchronized(sharedLock) {
return x;
}
Synchronized Vs Semaphore
Synchronized allows only one thread of execution to access the resource at the same time. Semaphore allows up to n (you get to choose n) threads of execution to access the resource at the same time.
Serialization:
Serialization is the process of writing the state of an object into byte stream(File). You can restore these objects by Deserialization.
Serializable interface:
Only an object that implements Serializable interface can be saved and restored by Serialization facilities.
Variables declared as transient and static are not serialized.
Why is serialization required?
In Java, everything is represented as objects.
So serialization is required to enable communication between 2 different independent applications. Object to file (serialization) then file to object (Deserialization)
How to serialize an object?
Step 1:
---------
In order to serialize an object, you need to ensure that the class of the object implements the java.io.Serializable interface,
import java.io.Serializable;
class TestSerial implements Serializable {
public byte version = 100;
public byte count = 0;
}
step 2:
---------
The next step is to actually serialize the object. That is done by calling the writeObject() method of the java.io.ObjectOutputStream class,
public static void main(String args[]) throws IOException {
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
TestSerial ts = new TestSerial();
oos.writeObject(ts);
oos.flush();
oos.close();
}
This writes the object to temp.out file.
Step 3:
---------
To re-create the object from the persistent file.
public static void main(String args[]) throws IOException {
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream oin = new ObjectInputStream(fis);
TestSerial ts = (TestSerial) oin.readObject();
System.out.println("version="+ts.version);
}
This creates replica of the original object
Externalization:
Writing the state of an object into byte stream(File) in compressed format is Externalization. Object should implement Externalizable interface.
sleep() vs wait() vs yield
sleep():
1)It is a static method on Thread class.
2)Call on a Thread.
3)It wakes after time expires
4) sleep doesn’t release lock while waiting.
wait():
1)It is a method on Object class.
2)Wait is called on a object, not a thread.
3)waiting thread can be awaked by calling notify and notifyAll.
4)wait releases the lock of object while waiting.
5)It must be called from synchronized context i.e. from block or method.
yield()
1)yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute
Why wait() notify() and notifyAll() are in Object class? Why some methods are in Thread class and some in object class?
Java object allows thread to communicate with each other and Locks are made available on object, so they are put in Object class
ExecutorService vs normal thread:
-ExecutorService can control the number of generated threads while for normal threads there is no control
eg. ExecutorService executorRoot = Executors.newFixedThreadPool(10);
-ExecutorService has 2 methods:
shutdown(): it will not accept new tasks and shut down after all running threads finish their current work.
shutdownNow(): it tries to destroy the ExecutorService immediately, but it doesn’t guarantee that all the running threads will be stopped at the same time
Wait for threads to finish executing:
executorService.shutdown();
while (!ex.awaitTermination(1, TimeUnit.MINUTES)) {
}
You can specify time in minutes or seconds. Waits until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
User Thread:
When we create a thread in java, by default it’s a user thread
Daemon threads
Daemon threads are low-priority threads whose only role is to provide services to user threads.
JVM does not wait for Daemon threads to finish executing. JVM will terminate this thread if user threads are finished executing
thread.join()
The join() method waits for a thread to die.When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.
Heap vs Stack:
Heap:
Objects are stored in Heap memory.It is the runtime data area.
Class instances and arrays are stored in heap memory.
Stack:
It stores method calls and returns, local variable(method variables).
Java Stack stores frames.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
Note:
No memory allocation happens at compile time, only at load and runtime.
String pool is inside Heap memory.
In short almost all are stored in Heap except method calls.
Which package is always imported by default?
The java.lang package is always imported by default.
Error vs Exception
Main difference on Error vs Exception is that Error is not meant to catch as even if you catch it you cannot recover from it. Example of error is OutOfMemoryError. On the other hand Exception can be caught and handled properly. Both Error and Exception are derived from java.lang.Throwable. Throwable class is derived from object class.
Two types of exception:
Unchecked Exception:
The exceptions that are not checked at compile time are called unchecked exceptions
Eg. ArrayIndexOutOfBoundsException, NullPointerException
CheckedExceptions:
Exceptions that are checked at compile-time are called checked exceptions
Eg. ClassNotFoundException, IOException, SQLException
What is the use of bin and lib in JDK?
bin contains all tools such as javac, applet viewer, awt tool etc., whereas lib contains all packages and variables
Can an unreachable object become reachable again?
Yes, an unreachable object may become reachable again. This happens when the object's finalize() method is invoked since finalization checks if reference to an object exist. This way the unreachable object becomes reachable again
What is the difference between abstract class and interface?-
1) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be abstract or non-abstract methods.
2)All methods declared within an interface must be implemented by the class that implements this interface
3) Interface has only public static and final variables.
4) Abstract class must have subclasses whereas interface can’t have subclasses.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row. By default, ResultSet object can be moved forward only and it is not updatable. Term "result set" refers to the row and column data contained in a ResultSet object.
ResultSetMetaData interface
The metadata means data about data i.e. we can get further information from the data. If you have to get metadata of a table like total number of column, column name, column type
etc. ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.Some of the methods are:
getColumnName(), getColumnType() etc.