☞Refer Core Java basics interview questions for a comprehensive list of Core Java Interview Questions.
What is encapsulation?
Encapsulation means keeping together the implementation (code) and the data it manipulates (variables). In Java a class contains the member variables (instance variables) and the code in methods. In a properly encapsulated Java class method defines how member variables can be used.
Read more about encapsulation here.
What is abstraction?
Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, Abstraction means abstracting/hiding the real working and we, as a user, knowing only how to use it.
Real world example would be a vehicle which we drive with out caring or knowing what all is going underneath.
Read more about abstraction here.Difference between abstraction and encapsulation?
Abstraction is more about hiding the implementation details. In Java abstraction is achieved through abstract classes and interfaces.
Encapsulation is about wrapping the implementation (code) and the data it manipulates (variables) with in a same class. A Java class, where all instance variables are private and only the methods with in the class can manipulate those variables, is an example of encapsulated class.
Read more about abstraction here and encapsulation here.What is Polymorphism?
Polymorphism, a Greek word, where poly means many and morph means change, thus it refers to the ability of an object taking many forms. The concept of polymorphism is often expressed as "One interface, multiple methods".
Read more about polymorphism here.
Where one general class may have the generic method and the derived classes (classes which extend the general class) may add their own specific method with implementation. At the time of execution "One interface" i.e. the general class will take "many forms" i.e. references of the derived classes.What is inheritance?
Inheritance is a mechanism, by which one class acquires, all the properties and behaviors of another class. The class whose members are inherited is called the Super class (or base class), and the class that inherits those members is called the Sub class (or derived class).
Read more about inheritance here.
The relationship between the Super and inherited subclasses is known as IS-A relationship.What Is a Class?
In object-oriented terms class provides a blue print for the individual objects created from that class. Once a class is defined it can be used to create objects of that type.
Read more about class here.What Is an Object?
In object-oriented terms object is an instance of the class, which gets its state and related behavior from the class. When a new class is created essentially a new data type is created. This type can be used to declare objects of that type.
Read more about object here.
An object stores its state in fields and exposes its behavior through methods.What is method overloading?
When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded. This process of overloaded methods is known as method overloading.
Read more about method overloading here.What is method overriding?
In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
Read more about method overriding here.What are JVM, JRE and JDK?
JVM
JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on.
JVM is platform dependent and different implementations of JVMs are available for specific platforms.JRE
JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.
JDK
JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.
Read more about JVM, JRE and JDK here.What is bytecode in Java or Why java is called platform independent?
Java programs are both compiled and interpreted which means -
When we do javac javaprogram, the java source code is compiled into a .class file which is actually a bytecode. The generated bytecode is portable and it's format is same across platforms.
After compilation, the interpreter reads the generated byte code & transforms it according to the native platform.
The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. So Java program is platform independent but JVM is platform dependent and different implementations of JVMs are available for specific platforms.Java is pass by value or pass by reference?
Java is pass by value for both primitive types as well as for objects.
Read more about Java pass by value or pass by reference hereWhat is package in Java?
A package is a namespace that organizes a set of related classes and interfaces. Packages also help in preventing naming conflicts.
Read more about Package in Java here
Packages also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.What are access modifiers in Java?
Access level modifiers are used to control the visibility of the class or the members of the class i.e. fields and methods.
Types of Access Modifiers- private - private modifier specifies that the member can only be accessed in its own class.
- default (or package-private) - If no specifier is used (which is known as default access) member is visible only within its own package.
- protected - protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
- public - public modifier specifies that member is visible to all classes everywhere.
What all access modifiers can be used with a class?
At the class level only two of the modifiers can be used, public or default.
Read more about Access Modifiers here
If a class is declared with the modifier public, that class is visible to all classes everywhere.
If a class has no modifier (the default), it is visible only within its own package.What all access modifiers can be used with class fields?
All the four types of access modifiers - public, protected, default, private can be used with variables declared in the class.
- If a field is declared as public then it is visible to all classes in the same package or other packages.
- If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
- If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
- If a field is defined private then that field can only be accessed in its own class.
What all access modifiers can be used with class methods?
All the four types of access modifiers - public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.
What all access modifiers can be used with constructors?
All the four types of access modifiers - public, protected, default, private can be used with constructors of the class.
- In case constructor of the class is private then the object of that class can be created by that class only.
- In case constructor is marked as protected then a subclass in different package can access the protected constructor.
- If a constructor is declared with no access specifier (default) then it can be accessed by any class in the same package.
- If a constructor is declared as public then it is visible to all classes in the same package or other packages.
What is automatic numeric promotion in Java?
In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.
As exp.byte a = 100; byte b = 50; int i = a * b;
In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression. Read more about automatic numeric promotion hereWhat is constructor?
In Java there is a special method provided to initialize objects when they are created. This special method which is used for automatic initialization is called Constructor.
Read more about constructor here.
Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a methodWhat is default constructor in Java?
When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class that is called default constructor.
Read more about constructor here.What is Parameterized Constructor in Java?
If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.
Read more about constructor here.What is constructor chaining in Java?
In case when we have a hierarchy of classes (inheritance) the constructors of the classes are invoked in an order. That order is known as constructor chaining.
Read more about constructor chaining here.
For Exp - If class A is super-class and there is Class B which is subclass of A. In that case if a new instance of class B is created, order in which constructors of Class A and Class B are executed is from super-class to subclass.What is constructor overloading in Java?
Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.
Read more about constructor overloading here.Are constructors from the super class inherited in the sub-class?
No constructors are not inherited in Java.
What is this in java?
this in java is a reference to the current object on which the method or constructor was invoked. this can be used inside any method or constructor to refer to the current object.
Read more about this here.What is super in java?
The super keyword in java is essentially a reference variable that can be used to refer to its immediate parent class.
Usage of super -- Invoke the constructor of the super class.
- Accessing the variables and methods of parent class.
What is automatic numeric promotion in Java?
In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.
As exp.byte a = 100; byte b = 50; int i = a * b;
In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression. Read more about automatic numeric promotion here.What is interface in Java?
Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
Interfaces look syntactically similar to classes, but they differ in many ways -- Interfaces don't have instance variables.
- In interfaces methods are declared with out any body. They end with a semicolon.
- Interface can't be instantiated.
- Interfaces don't have constructors.
- An interface is implemented by a class not extended.
- An interface can extend multiple interfaces.
Can an Interface be final?
No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.
Read more about interfaces here.Is it possible to declare an interface method static?
Not before Java 8, from Java 8 it is possible to have interface static methods.
Read more about interface here and interface static method here.What are interface default/defender methods?
With the release of Java 8, it is now possible to add default method in interfaces. With the addition of default method to an interface, addition of new method, to even an interface will not break the pre-existing code.
An interface default method is defined the same way a method will be defined in a class. One difference is that in interface default method is preceded by the keyword default
As Exp.public interface MyInterface { int method1(); // default method, providing default implementation default String displayGreeting(){ return "Hello from MyInterface"; } }
Read more about interface default method here.Can an Interface implement another Interface?
No, an interface can't implement another interface. Though, interface can extend another interface.
Read more about extending interface here.Can an Interface extend another Interface?
Yes,interface can extend another interface.
Read more about extending interface here.Is it possible to have final method in an interface?
No, whole idea of interface is to have abstract methods for which implementation is provided by the implementing classes. Making a method as final in interface will mean it can't be overridden which will mean implementing class can't provide an implementation for that mthod.
Read more about interfaces here.Is it possible to define a class inside an interface?
Yes. An interface can have an inner class. That class will be accessed by using InterfaceName.ClassName.
What is a nested interface?
An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.
Read more about nested interface here.What is a marker interface?
A marker interface is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface.
Read more about marker interfaces here.What is an abstract class?
An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.
Read more about abstract class here.Is it possible to have abstract method in a class that is not abstract?
No. If there is even a single abstract method in a class that class has to be declared as abstract.
Read more about abstract class here.Is it possible to instantiate an abstract class?
No. An abstract class can not be instantiated on its own, but abstract class can be used to create object references.
Read more about abstract class here.Is it possible to have an abstract class without any abstract method?
Yes. Even if there are no abstract methods in a class that class can still be declared as abstract. That abstract class still can not be instantiated.
Read more about abstract class here.Can you use abstract and final both with a method?
No. The whole idea of having a abstract method in a class is that it would be implemented by the inheriting class. Whereas making a method final means it can't be overridden thus can't be provided implementation in inheriting class. So using both of them is not possible.
Read more about abstract class here and about final here.What are the differences between abstract class and interface?
Abstract Class Interface Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
Note: From Java 8 interfaces can have default methods and static methods.Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only. Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final. Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods. Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor. Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces. Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method. Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract. Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses. What is Static variable in Java?
A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable.
Read more about static keyword here.What is static method in Java?
A static method is associated with the class rather than objects of the class. Static method can be called directly with the class name ClassName.static_method() rather than with the object of the class.
Read more about static method here.What is static block in Java?
A static block in a class is executed only once, when the class is first loaded, even before the main method.
Example of static block
public class StaticDemo { // static blank final variable static final int i; static int b; static { System.out.println("in static block"); i = 5; b = i * 5; System.out.println("Values " + i + " " + b); } }
Read more about static block here.Can we have static variable inside a method?
No. Since static variables belong to a class where as variables declared inside a method are local variables and belong to that method. So variables inside a method can be declared as final, but not static, public, protected or private.
Read more about static keyword here.Why can't we access non-static variable from static method?
OR
Why non-static variable can not be accessed from main method in Java?Static methods or fields can be accessed without even creating an instance of the class, we just need to qualify the static member with the class name and access it. But non-static members need instance of the class to be created to come into existence. That is the reason why non-static field or method can not be called from the static context.
Read more about Static reference to the non-static method or field error here.Can we overload static method?
Static methods can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.
Read more about static overloading here.Can we override static method?
Static methods can not be overridden in Java. Though it is possible to have a static method with same signature in sub-class but in that case sub-class method hides the super class method rather than overriding it.
Read more about static method overriding here.Why main method is static in Java?
When a class is loaded JVM needs an entry point (main method). JVM needs to access that main method with out creating an instance of the class, that is why main method is static.
If it is not declared as static then instance of the main class has to be created which may cause ambiguity.public class A { private int i; A(int i){ this.i = i; } public static void main(String args[]){ } }
Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static.
Read more about Why main method is static here.What is static import in Java?
In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.
As exp. - ClassName.static_method()With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. This shortens the syntax required to use a static member.
Read more about static import in Java here.What is final in Java?
final keyword in java has its usage in preventing the user from modifying a field, method or class.
- final field - A variable declared as final prevents the content of that variable being modified.
- final method - A method declared as final prevents the user from overriding that method.
- final class - A class declared as final can not be extended thus prevents inheritance.
What is a final blank variable?
A final variable can be initialized only once but it can be done in two ways.
- Value is assigned when the variable is declared.
- Value is assigned with in a constructor.
What if a list is declared as final, is it possible to add or remove values from that list?
When an object reference variable is declared as final, object fields can still be changed but the reference can't be changed.
So yes it is possible to add or remove values from the list even if the list is declared as final.But we can't change the reference of that list.
As Exp.final List tempList = new Arraylist(); tempList.add("1"); // permitted tempList = new ArrayList()// This will result in an error as we are trying to change the reference
What is a final method?
A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.
Read more about final method here.What is a final class?
A class declared as final can't be extended thus avoiding inheritance altogether.
Read more about final class here.
If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.What is covariant return type?
Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.
This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method. Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.
Read more about covariant return type here.What is strictfp in Java?
strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. Prior to JVM 1.2, floating-point calculations were strict; which meant, all intermediate floating-point results were represented as IEEE single or double precision only. As a consequence, errors of calculation (round-off errors), overflows and underflows would occur with greater frequency than in architectures which did intermediate calculations in greater precision.
Since JVM 1.2, intermediate computations are not limited to the standard 32 bit and 64 bit precisions. On platforms that can handle other representations e.g. 80-bit double extended on x86 or x86-64 platforms, those representations can be used, helping to prevent round-off errors and overflows, thereby increasing precision.
Read more about strictfp in Java here.What is Exception Handling?
Exception Handling in Java provides a way to handle a situation when an exception is thrown and shows a meaningful message to the user and continue with the flow of the program.
When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.
The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.
Five keywords used to manage Java exception handling
- try - Any code that might throw an exception is enclosed within a try block.
- catch - If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner.
- finally - The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block.
- throw - throw is used to manually thrown an exception.
- throws - Any exception that is thrown in a method but not handled there must be specified in a throws clause.
Explain the exception hierarchy in Java?
Throwable class is the super class of all the exception types. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions -
- Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.
- Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type
Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
Examples of error are StackOverflowError, OutOfMemoryError etc.
Below Exception there is a distinct subclass RunTimeExcpetion - RunTimeExcpetion and its descendants denote the exceptional conditions that are external to the application, and the application usually cannot anticipate or recover from them.
What is the difference between Checked Exception and Unchecked Exception?
Checked Exception is a direct subclass of Exception where as unchecked exception is a subclass of RunTimeException.
Checked exception should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception.
Failure to provide exception handling mechanism for checked exception result in compiler error whereas no compile time error for unchecked exception.
Checked exceptions are designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors.
Read more about difference between Checked Exception and Unchecked Exception here.What is the difference between error and exception?
Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.
Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
Examples of error are StackOverflowError, OutOfMemoryError etc.Is it necessary that each try block must be followed by a catch block?
No it is not mandatory that there should be a catch block after a try block. try block can have only a matching finally block. So there are these valid combnations try-catch-finally, try-catch, try-finally.
Read more about try-catch block here.What is finally block?
When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method.
As exp if a file was opened in a method and it was not closed in the end as some exception occurred then the resources may remain open consuming memory. finally provides that exception-handling mechanism to clean up.Code with in the finally block will be executed after a try/catch block has completed. The finally block will be executed whether or not an exception is thrown.
Read more about finally block here.Is it possible to have a finally block without catch?
Yes we can have a try-finally block, catch is optional. We can have these combinations try-catch-finally, try-catch, try-finally.
Read more about finally block here.Are you aware of any scenario when finally will not be executed?
According to Java docs. If the JVM exits (By explicitly using System.exit() or a JVM crash) while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Read more about finally here.What is a nested try statement?
A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement.
public class NestedTryDemo { public static void main(String[] args) { try{ System.out.println("In Outer try block"); try{ System.out.println("In Inner try block"); int a = 7 / 0; }catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); }finally{ System.out.println("In Inner finally"); } }catch (ArithmeticException e) { System.out.println("ArithmeticException caught"); }finally { System.out.println("In Outer finally"); } } }
Read more about nested try statement here.What are multiple catch blocks?
There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.
int a[] = {0}; try{ int b = 7/a[i]; }catch(ArithmeticException aExp){ aExp.printStackTrace(); }catch(ArrayIndexOutOfBoundsException aiExp){ aiExp.printStackTrace(); }
Read more about multiple catch blocks here.What is exception propagation?
When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.
Read more about exception propagation here.
The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.
If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation.What is throw keyword?
It is possible for a Java program to throw an exception explicitly that is done using the throw statement.
The general form of throw is-
We can get this throwableObject in 2 ways -
throw throwableObject;- By using the Exception parameter of catch block.
- Create a new one using the new operator.
try{ throw new NullPointerException(); }catch(NullPointerException nExp){ System.out.println("Exception caught in catch block of displayValue"); throw nExp; } }
Read more about throw keyword here.What is throws clause?
If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword.
Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).
General form of a method declaration that includes a throws clause
type method-name(parameter-list) throws exception-list { // body of method }
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Read more about throws clause here.Difference between throw and throws?
- throw is used to throw an exception.
- throws is used to declare an exception, in the method signature, that can be thrown from a method.
final Vs finally Vs finalize
- final - final keyword is used to restrict in some way. It can be used with variables, methods and classes.
When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank
final variable, which must be initialized in the constructor.
If you make a method final in Java, that method can't be overridden in a sub class.
If a class is declared as final then it can not be sub classed. - finally - finally is part of exception handling mechanism in Java. finally block is used with try-catch block. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc.
- finalize() - finalize() method is a protected method of java.lang.Object class. Since it is in Object
class thus it is inherited by every class. This method is called by garbage collector thread before removing an
object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object
final chance to cleanup before getting garbage collected.
protected void finalize() throws Throwable { //resource clean up operations }
- final - final keyword is used to restrict in some way. It can be used with variables, methods and classes.
When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank
final variable, which must be initialized in the constructor.
What are the rules of exception handling with respect to method overriding?
There are certain restrictions while overriding a method in case of exception handling in Java. Broadly there are two rules -
- If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.
- If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
- sub-class can declare the same exception as declared in the super-class method.
- subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
- subclass method can choose not to declare any exception at all.
What is the error in the following code?
class Parent{ public void displayMsg() throws IOException{ System.out.println("In Parent displayMsg()"); throw new IOException("Problem in method - displayMsg - Parent"); } } public class ExceptionOverrideDemo extends Parent{ public void displayMsg() throws Exception{ System.out.println("In ExceptionOverrideDemo displayMsg()"); throw new Exception("Problem in method - displayMsg - ExceptionOverrideDemo"); } }
Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error.
Read more about exception handling and method overriding here.What is multi-catch statement in Java 7?
Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.
catch(IOException exp){ logger.error(exp); throw exp; }catch(SQLException exp){ logger.error(exp); throw exp; }
With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol (|).
catch(IOException | SQLException exp){ logger.error(exp); throw exp; }
Read more about multi-catch statement in Java 7 here.What is try-with-resources or ARM in Java 7?
Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc.
Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly.
try { br = new BufferedReader(new FileReader("C:\\test.txt")); System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null){ System.out.println("Closing the file"); br.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-with-resources.
try(BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); }
Read more about try-with-resources in Java 7 here.When is custom exception class needed? How to create a custom exception class?
According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
- Do you need an exception type that isn't represented by those in the Java platform?
- Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
- Does your code throw more than one related exception?
- If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
What is thread in Java?
According to JavaDoc A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
How do we create thread in Java?
In Java there are two ways to create thread.
- By implementing the Runnable interface.
- By extending the Thread class.
Example code snippet using Runnable interface
class MyThread implements Runnable{ MyThread(){ Thread t = new Thread(this, "My Thread"); t.start(); }
Example code snippet using Thread class
class TestThread extends Thread{
and thenTestThread t = new TestThread(); // starting the thread t.start();
After the new thread is created, it will not start running until you call the start( ) method. Read more about How to create thread in Java here.What is the difference between thread and process?
- A process has a self-contained execution environment, Threads exist within a process - every process has at least one.
- Process are heavyweight tasks whereas threads are referred as lightweight processes as creating a new thread requires fewer resources than creating a new process.
- Each Process has its own separate address spaces, threads with in the same process share the process' resources, including memory and open files. This means that it's very easy to share data amongst threads, but it's also easy for the threads to bump on each other, which can lead to unpredictable scenarios.
- Inter process communication is expensive whereas inter thread communication is inexpensive and in Java can be achieved easily using wait and notify.
- Context switching from one process to another is expensive; context switching between threads is generally less expensive than in processes.
- Threads are easier to create than processes as separate address space is not required for a thread.
What are the different thread states?
- New - When a thread is created either by extending Thread class or implementing Runnable interface it is in "New State".
- Runnable - When we call start() method on the thread object that causes the thread to begin execution and it's the Java Virtual Machine that calls the run method of the thread.
- Blocked - When a resource is shared among various threads then a thread may go into blocked state as the resource may be used by another thread.
- Waiting - A thread that is waiting indefinitely for another thread to perform a particular action is in the waiting state.
- Timed_Waiting - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in timed_waiting state.
What are the thread priorities and how to set thread priority?
When a Java thread is created, it inherits its priority from the thread that created it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.
public final void setPriority(int newPriority)
Here newPriority specifies the new priority setting for the calling thread. The priority level ranges from 1 (least important) to 10 (most important) and the default priority level is 5.
In Thread class, three constants are provided to define min, max and default priority for a thread.public final static int MIN_PRIORITY = 1; public final static int NORM_PRIORITY = 5; public final static int MAX_PRIORITY = 10;
Read more about thread priorities in Java here.What does isAlive() method do in Java threading?
isAlive() method is the member of the Thread class and its general form is -
public final boolean isAlive()
isAlive() method tests if the thread it is called upon is alive. A thread is alive if it has been started and has not yet died. The isAlive( ) method returns true if the thread upon which it is called is still running, otherwise it returns false. If we have a thread -Thread t1 = new Thread(new MyRunnableClass(), "t1");
Then we can use isAlive to check if it is still running or not.System.out.println("t1 Alive - " + t1.isAlive());
Read more about isAlive() method here.What is join() method?
Join() method is used when you want to wait for the thread to finish. Its general form is -
public final void join() throws InterruptedException
This method waits until the thread on which it is called terminates. Read more about join() method here.Can we call run() method directly instead of start()?
When we call start() method on the thread that causes this thread to begin execution and it's the Java Virtual Machine that calls the run method of this thread.
Read more about Can we call run() method directly here.
If we directly call run method it will be treated as a normal overridden method of the thread class (or runnable interface). This run method will be executed with in the context of the current thread not in a new thread.Can we start the same thread twice in Java?
No. A thread can only be started once and any attempt to start the same thread twice will throw IllegalThreadStateException.
Read more about Can we start the same thread twice here.What are wait, notify, notifyall method used for in Java multi-threading?
Java provides inter-thread communication using the wait(), notify() and notifyAll() methods of the Object class.
- wait method - tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to sleep, until another thread invokes the notify() or notifyAll() method for this object.
- notify method - Wakes up a single thread that is waiting on this object's monitor. If more than one threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
- notifyAll method - wakes up all the threads that called wait( ) on the same object.
What is the difference between notify() and notifyAll()?
- Notify method wakes up a single thread that is waiting to acquire a lock on the object. If more than one threads are waiting on this object, one of them is chosen to be awakened.
- NotifyAll method wakes up all the threads that called wait on the same object. Note that only one of these threads will get a lock to the object.
Why wait(), notify() and notifyAll() methods are in object class?
wait() and notify() work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait and through notify (or notifyAll) thread which are waiting on the object's monitor are notified that thread can wake up. Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class.
wait, notify and notifyAll() are used for inter-thread communication. But threads themselves have no knowledge of each others status. It is the shared object among the threads that acts as a communicator among the threads. Threads lock an object, wait on an object and notify an object.
Read more about Why wait(), notify() and notifyAll() methods are in object class here.When notify method is called does the thread which comes out of waiting start executing instantly?
No, thread which comes out of waiting because of the notify() method will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread just changes to the runnable state and it is ready to be scheduled again. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object.
Read more about wait, notify, notifyall here.Why wait, notify and notifyAll must be called inside a synchronized method or block?
wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor. Object's lock is acquired by a thread only when it is executing in a synchronized context. So it makes sense to use wait() method, which asks thread to release the lock only in synchronized context.
Same way; when object's notify() or notifyAll() method is called, single thread (in case of notify) or all of the threads (in case of notifyAll), waiting for the object's lock change state to runnable and contend for the object's lock, and the thread that gets the lock starts execution. Here again, notify and notifyAll can inform other threads, that the object's lock can be acquired now, only if these methods are called from the synchronized object.
Read more about Why wait, notify and notifyAll must be called inside a synchronized method or block here.What is spurious wakeup?
Once wait is called on an object the thread that is currently executing with in the synchronized context waits until notify or notfyAll method is called. But there is a possibility that a waiting thread resumes again even when notify() or notifyAll() are not called (this will rarely occur in practice). This is known as spurious wakeup.
To guard against it the recommendation is that; call to wait() method should be with in a loop that checks the condition on which the thread is waiting.What does yield method do?
Yield - A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. The executing thread is suspended and the CPU is given to some other runnable thread. This thread will wait until the CPU becomes available again.Technically, in process scheduler's terminology, the executing thread is put back into the ready queue of the processor and waits for its next turn.
Read more about yield method here.
yield is a static method of the Thread class. When called it will work on the currently executing thread, not on any particular thread.What is the difference between sleep and wait?
- The very first difference is that sleep is defined as a static method in Thread class and operates on the currently executing thread. Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
- Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). If not called from a synchronized context will result in a IllegalMonitorStateException being thrown. With sleep method there is no such mandatory condition it doesn't need to be called from a synchronized context.
- Wait method will release the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block. Sleep method if called from a synchronized block or method will not release the lock so another won't get a chance to enter the synchronized block.
Read more about difference between sleep and wait here.why Thread.sleep() and yield() methods are declared as static?
yield and sleep methods are used to work on the currently executing thread. Thus these methods are static so that you don't call it on any other thread.What is synchronization in Java multi-threading?
In a multithreaded environment when more than one thread are trying to access a shared resource we need to have some way to ensure that the resource will be used by only one thread at a time. The process by which it is ensured is called synchronization.
Read more about synchronization in Java multi-threading here.What is a synchronized block?
It is not always needed to synchronize the whole method, let's say we have a 100 line code method, out of which critical section (shared resource) is only 7 lines then it makes sense to synchronize only those 7 lines rather than synchronizing the whole method. That is known as synchronized block or statement.
class Message{ public void displayMsg(String msg){ System.out.println("Inside displayMsg method " + Thread.currentThread().getName()); synchronized(this){ System.out.print("**" + msg); try { Thread.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("*"); } } }
Read more about synchronization in Java multi-threading here.What is race condition in multi-threading?
Race condition occurs in a multi-threaded environment when more than one thread try to access a shared resource (modify, write) at the same time. Note that it is safe if multiple threads are trying to read a shared resource as long as they are not trying to change it. Since multiple threads try to race each other to finish executing a method thus the name race condition.
Read more about race condition in Java multi-threading here.What is a deadlock in Multi-threading?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. To describe it in a simple manner let's assume there are two threads Thread-1 and Thread-2 and two objects obj1 and obj2. Thread-1 already holds a lock on obj1 and for further processing it needs a lock on obj2. At the same time Thread-2 holds a lock on obj2 and wants a lock on obj1. In that kind of scenario both threads will be waiting for each other forever to release lock they are already holding thus creating a deadlock.
Read more about deadlock in Multi-threading here.Write a program to create deadlock in Java.
A deadlock can be created by having nested synchronized blocks where lock on objects are acquired in a reverse manner. i.e. if there are two objects obj1 and obj2 then first thread tries to acquire lock in sequence obj1 and then obj2. In the same time second thread tries to acquire lock in sequence obj2 first and then obj1.
class Test{ private final String name; public Test(String name){ this.name = name; } public String getName() { return this.name; } } class ThreadA implements Runnable{ private Test test1; private Test test2; ThreadA(Test test1, Test test2){ this.test1 = test1; this.test2 = test2; } @Override public void run() { synchronized(test1){ System.out.println("" + test1.getName()); synchronized(test2){ System.out.println("Reached here"); } } } } class ThreadB implements Runnable{ private Test test1; private Test test2; ThreadB(Test test1, Test test2){ this.test1 = test1; this.test2 = test2; } @Override public void run() { synchronized(test2){ System.out.println("" + test2.getName()); synchronized(test1){ System.out.println("Reached here"); } } } } public class DeadLockDemo1{ public static void main(String[] args) { Test test1 = new Test("Test-1"); Test test2 = new Test("Test-2"); Thread t1 = new Thread(new ThreadA(test1, test2)); Thread t2 = new Thread(new ThreadB(test1, test2)); t1.start(); t2.start(); } }
Thread t1 will start execution of run method in ThreadA and acquire lock on object test1 and then try to acquire lock on object test2. Meanwhile Thread t2 will start execution of run method in ThreadB and acquire lock on object test2 and then try to acquire lock on object test1. So both threads are trying to acquire a lock which is already held by another thread. Thus causing a deadlock.
Read more about deadlock in Multi-threading here.What is a thread local variable?
In Java there is a class called ThreadLocal which provides another way of thread-safety apart from synchronization. Usually when we have multiple threads sharing an object we need to synchronize the critical section of the code in order to make it thread safe.
Read more about thread local variable here.
ThreadLocal class provides thread-local variables where each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Since each and every threadhas its own copy of the object so explicit synchronization is not needed to provide thread safety.
Related Topics