Core Java Interview Questions and Answers
This is a Collection of very important core java interview questions with answers.
These questions will help students and job seekers to gain confidence to appear and get success in java interviews.
Lot of importance is given to a candidate’s ability to answer core java questions in a java job interview.
For private Online Core Java Training with java interview preparation you may contact me.
1. What is a class?
A class is a user defined datatype. It is a frame of all the objects that can be created using it. A class can contain data properties and functional properties.
int x,y;// instance variables declaration
void fire()//function definition
System.out.println("Firing from "+x+" "+y);
2. What is an object?
An object is an instance of a class. Each object will contain its own copies of the instance variables and the functions defined in a class. To create an object we use the new keyword.
- Soldier s1=new Soldier();
new Soldier() will create an object and make s1 is a reference variable of Soldier type that refers to the Soldier object created.
3. What is difference between instance variable and reference variable?
The data properties in a class are declared with variables. These variables are called instance variables. Example in the Soldier class we have declared two data properties the x coordinate and the y coordinate representing the location of a soldier. These data properties are called instance variables.
Each object of the Soldier class will have its own copies of the instance variable. e.g the first soldier object will have its own x and y and the second soldier object will have its own copy of x and y.
Reference variable is the variable that can refer to objects. Eg Soldier s1 is a Soldier type reference variable that can refer to Soldier type of objects.
4. Explain garbage collection in java.
When an object in the memory doesn’t have any reference variable pointing to it, java considers it a useless object, unnecessarily occupying memory. Java periodically searches for such type of hanging objects and removes them from memory. This procedure is called automatic garbage collection. We can tell the jvm to start the garbage collection by calling the function System.gc()
5. What is function overloading?
Function overloading is one type of polymorphism in which the function name is same but the parameter list is different. The number or nature of the parameters may be different.
6. What is a Constructor and its use?
A Constructor is just like a function with the same name as the class name and no return type, not even void. Constructors are generally used to initialize instance variables during object creation.
7. What is this keyword in java?
The keyword “this” refers to the current class object.
8. What is super keyword in java?
The “super” keyword in java refers to the parent class object.
9. What is static keyword in java?
The keyword static can be put in front of a variable , function or a block in java. To access a static variable or a static function we don’t need to create an object. We cann access a static variable or a function directly through the class name e.g classname.function() or classname.variable.
A static variable is shared among all objects of the class.
10. Can we make the constructor of a class static?
We know that the static context (methods, blocks, variables) belongs to the class and not the object. Constructors can only be invoked when an object is created. Therefore, it makes no sense to make constructors static. The compiler will alert you if this is attempted.
11. Can static methods be overridden?
No we cannot override static methods. But we can overload static methods.
12. What is the significance of the main function being static?
The function main is the starting point of program execution. There is no need for the jvm to create an object of the class to access the main function. So the main function is made static.
13. What happens if the static keyword is not included in the main method signature in Java?
If we don’t include the ‘static’ keyword in the main method definition, the compilation of the program will go through without any issues but when we’ll try to execute it, a “NoSuchMethodError” error will be thrown.
14. What is the use of inheritance in programming?
The main benefit of inheritance is code reusability. The properties of the parent class are available in the child classes. The child class inherit from the parent class using the extends keyword.
15. Does java support multiple inheritance?
Java doesn’t support multiple inheritance through classes but supports through interfaces. Class A extends B,C is not possible but class A implements X,Y is possible provided X and Y are interfaces.
16. What is difference between Path and CLASSPATH?
Path is an environment variable that guides the operating system from where it will search for executable files.
CLASSPATH is an environment variable that helps to educate the JVM from where it will start searching for .class files. generally we store the root of the package heirarchy in the CLASSPATH environment variable.
We also store the location of external jar files in the environment variable, so that the jvm can locate the class files within it.
17. What is function overriding?
Same function name and same parameter list, and can happen during inheritance only.
18. Explain run time polymorphysm.
Java resolves dynamically at run time, which function to call, based on which sub class is referred by the super class reference variable just before the function is called.
Figure f=new Rectangle(); f.area();
In the above code the area of the rectangle class get called because just before the function is called, the reference variable is pointing to a Rectangle object.
19. What is an abstract class?
Any class can be made abstract by just putting the abstract keyword in front of the class. But if a class contains one or more abstract functions, we are bound to make the class abstract.
We cannot create an object of an abstract class.
Abstract classes are generally used to create the frame of the project, or the top level class.
Subclass of an abstract class has to provide implementation of all the abstract functions present in the super class, else the subclass will also become abstract.
We can also implement run time polymorphism through abstract classes.
20. What is Object class?
Object class is an inbuilt class present in the java.lang package. It is the super class of all classes in java.
Whenever we create a class, by default it is the subclass of the object class. We can override non final functions of the Object class in any class eg toString(), equals() etc.
21. What is the use of toString function?
The toString function gets automatically inherited in all java classes from the Object class. We can override the toString function. When ever we print an object of a class, by default the toString function of the class gets called. So if we want to give a customizable output when printing an object, we can override the toString function.
22. Explain about different access specifiers.
The different access specifiers are public, private, protected and the default.
private properties are accessible from only within the same class.
public properties are accessible from anywhere.
no modifier properties are accessible only from within the same package.
protect properties are accessiable from the same package, but out side the package it is accessiable provided it is done from a sub class.
23. What are the differences between an abstract class and an interface?
An abstract class can contain both function definitions and function declarations, but an interface can contain only function declarations.
An abstract class is extended by using the extends keyword while an interface is implemented using the implements keyword.
Multiple inheritance is not supported through classes or abstract classes but is supported through interfaces.
24. What is final keyword in java?
The final keyword in java can be used infront of a variable, function or a class.
If a final keyword is placed infront of a variable, it acts like a constant. It cannot be modified.
Eg final int YES=100;
By convention final variables are in upper case. They are declared and initilized in the same line.
Function defined as final cannot be overridden in the subclasses.
Classes defined as final cannot be subclassed or inherited.
25. What are wrapper classes, and their use?
Java provides special classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.
Most of the collection classes store objects and not primitive data types. Wrapper classes also provide many utility methods. And since we create instances of these classes we can store them in any of the collection classes and pass them as a collection. Also we can pass them as method arguments where a method expects an object.
26. What is an exception in java?
Exceptions are run time errors. e.g int i=1/0; This code doesn’t show any error during compile time, but when we run the code we get an ArithmeticException.
27. What is exception handling?
When we run a program that has error, java creates an appropriate exception type of object and throws it. Then the default exception handler of java handles the exception. But the default exception handler stops the program execution abruptly and gives a non understandable output.
So we are not satisfied by the default exception handler’s exception handling. So we want to handle the exception on our own so that the program will not stop abruptly and also give a non understandable output. We can do exception handling on our own using try and catch block.
28. What is the use of printStackTrace() method?
It helps to trace the exception step by step. It helps to find how the exception occured step by step.
29. Explain custom exception class.
We need a custom exception class to represent a custom problem. There are many inbuilt exception classes in java like ArithmeticException that represents arithmetic problems, ArrayIndexOutOfBounds exception to represent array related problems. But we need custom exception classes to represent custom problems, or our own problems. e.g ProductNotFoundException is a custom exception class representing a problem which occurs if a product is not found during the search. To create a custom exception class we have to extend the inbuilt Exception class.
30. Explain the use of throw keyword.
The throw key word is used to manually throw exception objects. If there is a division by zero or array problem java creates an appropriate exceptin object and throws it. But if there is a custom problem, java will not throw the exception but we have to manually throw the exception objects on our own using the throw keyword.
if(productNotFound) throw new NoProductFoundException();
Here NoProductFoundException is a custom exception class. If product is not found then we are manually creating an object of NoProductFoundException class and throwing it using throw keyword.
31. What is the use of throws keyword?
The throws keyword is used to delegate the exception handling mechanism to the caller of the function. When we define a function and we don’t want to put try and catch block than we can use throws keyword. The caller of the function has to put the try and catch blocks, or handel the exception.
static void fun() throws ProductNotFoundException
32. What is the difference between checked and unchecked exceptions?
Checked exceptions are those exceptions that cannot be handled by the default exception handler of java. So we have to manually handle the exception using try catch block. All the custom exceptions are checked exceptions.
Unchecked exceptions are those exceptions that can be handled by the default exception handler of java. eg ArithmeticException, NullpointerException etc.
33. What is Thread in Java?
A thread is a light weight process. Using thread multiple activities can be done within a single process. Thread based multitasking is called multithreading. Thread is an inbuilt class in java in the java.lang package.
34. What is Multithreading and its advantage?
Thread based mutitasking is called multithreading. Main advantages of using mutithreading are
- Multiple things can be done simultaneously in a process.
- Maximum utilization of the cpu. Cpu is very fast as compared to Input Output. When one thread is idle, another thread gets chance.
35. How to Create Multiple Threads?
There are two ways to create multiple threads. Either by implementing the Runnable interface or extending the Thread class.
Step 1: Create a child class that implements the runnable interface.
Step 2: Provide the working of the thread inside the run method
Step 3: Create another class containing the main function.
Step 4: Inside the main, create an object of the child class and pass it into the threads constructor.
Step 5: Then call the start function on the thread object created. This will invoke the run method defined
in the child class.
Check Detail Example >> How to Create Threads in Java
36. What is Synchronization?
Synchronization is a way to ensure that only one thread can access a resource at a particular time. Synchronization can be done using two way. Method level synchronization, and object level synchronization. Method level synchronization can be done by putting synchronized keyword in front of a function. While object level synchronization can be done through the help of synchronized block.
37. Which functions are used for inter thread communication?
Inter thread communication can be done in java using the functions wait(), notify() and notifyAll().
wait() function will make a thread to go to sleep until it is woken up using notify().
notify() function will wake up the the recent thread on whom wait() had been called.
notifyAll() function will wake up all the previous threads on whom wait() had been called.
38. Explain System.out.println()
System is an inbuilt class in java. “out” is a PrintStream type of stream object connected with the console, and println() is a function present in the PrintStream class. So when we want to display something in the console we use System.out.println().
39. What is Java Virtual Machine or JVM?
The JVM or Java Virtual Machine is a virtual machine that runs java files in a portable way. It is a specification that provides runtime environment in which java byte code can be executed. Jvm calls the main method present in a java code. Jvm is a part of the JRE(Java Runtime Environment). JVM helps to make java code platform independent.
40. What is Jit Compiler?
Jit Compiler or Just in Time Compiler is an essential part of the JRE , that improves the performance of Java™ applications by compiling bytecode to native machine code at run time. The JIT compiler is able to perform certain simple optimizations while compiling a series of bytecode to native machine language.
41. Is java a pure object oriented language?
No java is not a pure object oriented language because it also supports primitive data types – byte, boolean, char, short, int, float, long, and double.
Please check again we are updating this with more Core Java interview questions