Java Interview Questions!!
Java Interview Questions!!
Email: trohit3459@gmail.com
Basics of java
1. Explain JDK, JRE and JVM?
[JDK=JRE+DE TOOLS] [JRE=JVM+INBUILT LIB] [JVM=JIT+ INTERPETRE]
JDK is a software development kit whereas JRE is a software bundle that allows Java program
to run, whereas JVM is an environment for executing bytecode. The full form of JDK is Java
Development Kit, while the full form of JRE is Java Runtime Environment, while the full form of
JVM is Java Virtual Machine
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
Method Description
public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws
causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
45. What is difference between " equals() " and " == " in java?
Ans. equals() – it is a method present in Object class which is used to compare the address of two
objects. It can be overridden and can be used o compare the state of the object.
(==) Equality Operator – It is an operator used to compare address of 2 object.
46. What is String and explain atleast 6 inbuilt methods of String?
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an
immutable object which means it is constant and can cannot be changed once it has been created.
1. char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if
index<0||>= length of String.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode
value of each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the
case during comparison.
6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the
specified offset index) is having the specified prefix or not.
7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes
then it returns true else false.
8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
9. int hashCode(): It returns the hash code of the string.
10. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the
string.
String Buffer: - It is a final class extending object class and implementing CharSequence,
Serializable and Appendable interfaces.
String Buffer is a ‘mutable’ class, we can modify the values present inside the created object.
String Buffer is synchronized and it is thread safe.
String Builder: - It is a final class extending object class and implementing CharSequence,
Serializable and Appendable interfaces.
StringBuilder is unsynchronized and it is thread unsafe.
Exception & Exception Handling
51. Difference between Error and Exception?
UNCHECKED EXCEPTION: - These are the exceptions that are not checked at compile time. In
Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything
else under throwable is checked.
55. How to write custom exceptions in java and why we need custom exception?
//class representing custom exception
class MyCustomException extends Exception {
}
//class that uses custom exception MyCustomException
public class Custom_Ex2{
// main method
public static void main(String args[]) {
try {
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex) {
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
System.out.println("rest of the code...");
}
}
56. Without having catch block, is it possible to have only try block and finally block?
Yes, It is possible to have a try block without a catch block by using a final block.
As we know, a final block will always execute even there is an exception occurred in a try block, except
System.exit() it will execute always.
public class TryBlockWithoutCatch {
public static void main(String[] args) {
try {
System.out.println("Try Block");
} finally {
System.out.println("Finally Block");
}
}
}
The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method
of Java’s throwable class which prints the throwable along with other details like the line number and
class name where the exception occurred.
printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five methods in
your code cause an exception, printStackTrace() will pinpoint the exact line in which the method
raised the exception.
59. Is it possible to keep any statements in between try , catch and finally block?
No, we cannot write any statements in between try, catch and finally blocks and these blocks form
one unit.
try{
// Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
// Catching the exceptions here
}
// We can't keep any statements here
finally{
// finally block is optional and can only exist if try or try-catch
block is there.
// This block is always executed whether exception is occurred in the
try block or not
// and occurred exception is caught in the catch block or not.
// finally block is not executed only for System.exit() and if any
Error occurred.
}
60. Is it possible to only include a try block without the catch and finally block?
No.
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
Syntax error, insert "Finally" to complete BlockStatements
Iterator ListIterator
Iterator goes in Listiterator moves I both direction
Forward Direction Both Directions
iterator has two methods ListIterator has four methods
next()--> printing next obj in list next()---> printing next obj in list
hasNext()--> checking whether it has hasNext()----> checking whether it has next obj or not
next obj or not previous()--->printing Previous obj in list
hasPrevious()--->checking whether it has previous obj or
not
75. If we use duplicate key with some value in map what will happen?
If you try to insert the duplicate key, it will replace the element of the corresponding key.
Advanced Questions
77. What is multi-threading?
Ans. Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a
lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking. However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Runnable
• Runnable is a functional interface which is used to create a thread.
• It has only abstract method run()
• Multiple threads share the same objects.
1. Definition final is the keyword and finally is the block in finalize is the method in
access modifier which Java Exception Java which is used to
is used to apply Handling to execute the perform clean up
restrictions on a class, important code whether processing just before
method or variable. the exception occurs or object is garbage
not. collected.
2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the
finalize method performs
variable becomes important code even if
the cleaning activities
constant and cannot be exception occurs or not.
with respect to the object
modified. (2) finally block cleans
before its destruction.
(2) final method cannot up all the resources used
be overridden by sub in try block
class.
(3) final class cannot be
inherited.
4. Execution Final method is Finally block is finalize method is
executed only when we executed as soon as the executed just before the
call it. try-catch block is object is destroyed
executed.