Core Java Interview Questions and Answers
1) What is Java?
Java is a simple, high-level, secure, platform-independent, multithreaded, and object oriented programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own runtime environment as JRE and API.
2) What is the difference between JDK, JRE, and JVM?
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java byte code can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK
The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
Q3. What is the difference between Encapsulation and Abstraction?
Ans. 1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level
2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.
4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.
Q4. What is Polymorphism in Java ?
Ans. Polymorphism means the condition of occurring in several different forms.
Polymorphism in Java is achieved in two manners
1. Static polymorphism is the polymorphic resolution identified at compile time and is achieved through function overloading whereas
2. Dynamic polymorphism is the polymorphic resolution identified at runtime and is achieved through method overriding.
Update Your Skills form Our Experts: Core Java Online Training
Q5. What is a final method ?
Ans. It’s a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.
Q6. What is the difference between StringBuffer and String class ?
Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
The String class represents character strings. All string literals in Java programs, such as “abc” are constant and implemented as instances of this class; their values cannot be changed after they are created.
Q7. What are Default Methods?
Ans. With Java 8, We can provide method definitions in the Interfaces that gets carried down the classes implementing that interface in case they are not overridden by the Class. Keyword “default” is used to mark the default method.
Q8. What is garbage collection ?
Ans. The garbage collection is a facility wherein a program runs on the Java Virtual Machine which gets rid of objects, which are not being used by a Java application anymore. It is a form of automatic memory management and recollection.
Update Your Skills form Our Experts: Core Java Online Training
Q9. What is abstract class or abstract method?
Ans.We cannot create instance for an abstract class. We can create instance for its subclass only. By specifying abstract keyword just before class, we can make a class as abstract class.
public abstract class MyAbstractClass{
}
Abstract class may or may not contains abstract methods. Abstract method is just method signature, it does not containes any implementation. Its subclass must provide implementation for abstract methods. Abstract methods are looks like as given below:
public abstract int getLength();
Q10. When to use LinkedList or ArrayList?
Ans. Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insertion if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.
Q11. Can we override static method?
Ans.We cannot override static methods. Static methods are belongs to class, not belongs
to object. Inheritance will not be applicable for class members
Q12. What is the difference between super() and this()?
Ans.super() is used to call super class constructor, whereas this() used to call constructors in the same class.
Q13. What is the purpose of garbage collection?
Ans.The garbage collection process is to identify the objects which are no longer referenced or needed by a program so that their resources can be reclaimed and reused. These identified objects will be discarded.
Q14. Explain public static void main(String args[])
Ans.Here public is an access modifier, which means that this method is accessible by any class.
static – static keyword tells that this method can be accessed without creating the instance of the class.
void – this main method returns no value.
main – It is the name of the method.
String args[] – The args is an array of String type. This contains the command line arguments that we can pass while running the program.
Q15. What is the base class of all classes?
Ans.java.lang.Object is the base class (super class) of all classes in java.
Update Your Skills form Our Experts: Core Java Online Training
Q16. What is a path and classPath in Java?
Ans.Path specifies the location of .exe files. Classpath specifies the location of bytecode (.class files).
Q17. What is Type casting in Java?
Ans.When we assign a value of one data type to the different data type then these two data types may not be compatible and needs a conversion. If the data types are compatible (for example assigning int value to long) then java does automatic conversion and does not require casting. However if the data types are not compatible then they need to be casted for conversion.
For example:
//here in the brackets we have mentioned long keyword, this is casting
double num = 10001.99;
long num2 = (long)num;
Q18. What is an Array?
Ans.An array is a collection (group) of fixed number of items. Array is a homogeneous data structure which means we can store multiple values of same type in an array but it can’t contain multiple values of different types. For example an array of int type can only hold integer values.
Q19. Four main principles of OOPS Concepts?
Ans.
- Inheritance
- Polymorphism
- Data Encapsulation
- Abstraction
Q20. Can we overload a method by just changing the return type and without changing the signature of method?
Ans.No, We cannot do this. To overload a method, the method signature must be different, return type doesn’t play any role in method overloading.
Update Your Skills form Our Experts: Core Java Online Training
Q21. What is static and dynamic binding in Java?
Ans.Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.
Q22. What is the difference between abstract class and interface?
Ans.
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.
Q23. What is static block?
Ans.A static block gets executed at the time of class loading. They are used for initializing static variables.
Q24. Explain super keyword in Java?
Ans.super keyword references to the parent class. There are several uses of super keyword:
- It can be used to call the superclass(Parent class) constructor.
- It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
- To call the constructor of parent class.
Q25. Use of final keyword in Java?
Ans.
Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security.
Q26. What are Packages in Java?
Ans. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations).
Q27. What are the types of exceptions?
Ans.There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.
Q28. What is throw keyword in exception handling?
Ans.The throw keyword is used for throwing user defined or pre-defined exception.
Q29. What is throws keyword?
Ans.If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.
Update Your Skills form Our Experts: Core Java Online Training
Q30. Can we have a try block without catch or finally block?
Ans.No, we cannot have a try block without catch or finally block. We must have either one of them or both.
Q31. Can we have multiple catch blocks following a single try block?
Ans.Yes we can have multiple catch blocks in order to handle more than one exception.
Q32. Is it possible to have finally block without catch block?
Ans.Yes, we can have try block followed by finally block without even using catch blocks in between.
Q33. Can we handle more than one exception in a single catch block?
Ans.Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.
Q34. When a finally block does not get executed?
Ans.The only time finally won’t be called is if you call System.exit() or if the JVM crashes.
Q35. What is Multithreading?
Ans.Executing several tasks at a time, where each task is a separate independent part of a same process. Each separate independent part of a program is called as a Thread. In short the process of executing multiple threads simultaneously is known as multithreading.
Q36. How can we create a thread in java and which is the recommended way?
Ans.There are following two ways of creating a thread:
1) By Implementing Runnable interface.
2) By Extending Thread class.
Implementing Runnable interface is the recommended way to create a Thread.
Update Your Skills form Our Experts: Core Java Online Training
Q37. What is difference between wait and sleep methods in java?
Ans.sleep():It is a static method on Thread class. It makes the current thread into the “Not Runnable” state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired.
wait(): It is a method on Object class. It makes the current thread into the “Not Runnable”state. Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block. The call to wait() releases the acquired lock.
Q38. What is difference between yield and sleep?
Ans. yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.
Q39. What is Serialization and de-serialization?
Ans. Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization.
Q40.What is a transient variable?
Ans.
1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.
Q41. What is the difference between Iterator and Enumeration?
Ans.
1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().
Update Your Skills form Our Experts: Core Java Online Training
Q42. What are the restrictions that are applied to the Java static methods?
Ans. Two main restrictions are applied to the static methods.
- The static method can not use non-static data member or call the non-static method directly.
- this and super cannot be used in static context as they are non-static.
Q43. What are the advantages of passing this into a method instead of the current class object itself?
Ans. As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.
- “this” is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
- “this” can be used in the synchronized block.
Q44. Can we modify the throws clause of the super class method while overriding it in the subclass?
Ans. Yes, we can modify the throws clause of the super class method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.
- If the super class method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
- If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
Q45. What are the states in the lifecycle of a Thread?
Ans. A thread can have one of the following states during its lifetime:
- New: In this state, a Thread class object is created using a new operator, but the thread is not alive. Thread doesn’t start until we call the start() method.
- Runnable: In this state, the thread is ready to run after calling the start() method. However, the thread is not yet selected by the thread scheduler.
- Running: In this state, the thread scheduler picks the thread from the ready state, and the thread is running.
- Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.
- Dead/Terminated: A thread is in terminated or dead state when the run() method exits.
Q46. What is the difference between List and Set?
Ans. The List and Set both extend the collection interface. However, there are some differences between the both which are listed below.
- The List can contain duplicate elements whereas Set includes unique items.
- The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order.
- The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class.
- The List interface can allow n number of null values whereas Set interface only allows a single null value.
Q47. What is the difference between Set and Map?
Ans. The differences between the Set and Map are given below.
- Set contains values only whereas Map contains key and values both.
- Set contains unique values whereas Map can contain unique Keys with duplicate values.
- Set holds a single number of null value whereas Map can include a single null key with n number of null values.
Update Your Skills form Our Experts: Core Java Online Training
Q48. What is the difference between Collection and Collections?
Ans. The differences between the Collection and Collections are given below.
- The Collection is an interface whereas Collections is a class.
- The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.
- The Collection interface provides the methods that can be used for data structure whereas Collections class provides the static methods which can be used for various operation on a collection.
Q49. What is the advantage of the generic collection?
There are three main advantages of using the generic collection.
- If we use the generic class, we don’t need typecasting.
- It is type-safe and checked at compile time.
- Generic confirms the stability of the code by making it bug detectable at compile time.
Q50. How to remove duplicates from ArrayList?
There are two ways to remove duplicates from the ArrayList.
- Using HashSet:By using HashSet we can remove the duplicate element from the ArrayList, but it will not then preserve the insertion order.
- Using LinkedHashSet:We can also maintain the insertion order by using LinkedHashSet instead of HashSet.
The Process to remove duplicate elements from ArrayList using the LinkedHashSet:
- Copy all the elements of ArrayList to LinkedHashSet.
- Empty the ArrayList using clear() method, which will remove all the elements from the list.
- Now copy all the elements of LinkedHashset to ArrayList.
Also Read More Top Core Java Interview Question and Answers