Core Java Interview Questions and Answers For Freshers and Experienced
If you are thinking to build a career in Java programming, you need to crack an interview in which you will be asked several Core Java Interview Questions and Answers as listed below.
#1 What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.
#2 List the features of the Java Programming language.
There are the following features in Java Programming Language.
- Simple: Java is easy to learn. The syntax of Java is based on C++ which makes it easier to write the program in it.
- Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
- Portable: Java supports the read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
- Platform Independent: Java is a platform-independent programming language. It is different from other programming languages like C and C++ which need a platform to be executed. Java comes with its platform on which its code is executed. Java doesn’t depend upon the operating system to be executed.
- Secured: Java is secured because it doesn’t use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
- Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
- Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn’t exist in Java.
- Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
- High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is “close” to native code. It is still a little bit slower than a compiled language (e.g., C++).
- Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
- Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
- Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand, it also supports functions from its native languages, i.e., C and C++.
#3 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 bytecode can be executed. It is a specification that 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 that 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. The Java Runtime Environment is a set of software tools that are used for developing Java applications. It is used to provide a 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
JDK is an acronym for Java Development Kit. It is a software development environment that is used to develop Java applications and applets, it physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
- Standard Edition Java Platform
- Enterprise Edition Java Platform
- Micro Edition Java Platform
#4 What do you mean by Constructor?
A constructor can be explained in detail with enlisted points:
- When a new object is created in a program a constructor gets invoked corresponding to the class.
- The constructor is a method that has the same name as the class name.
- If a user doesn’t create a constructor implicitly a default constructor will be created.
- The constructor can be overloaded.
- If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.
#5 What is meant by the Local variable and the Instance variable?
Local variables are defined in the method and scope of the variables that exist inside the method itself.
An instance variable is defined inside the class and outside the method and the scope of the variables exists throughout the class. This is the most important Core Java Interview Questions and Answers
#6 What is a Class?
All Java codes are defined in a Class. It has variables and methods.
Variables are attributes that define the state of a class.
Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.
Example:
public class Addition{ //Class name declaration int a = 5; //Variable declaration int b= 5; public void add(){ //Method declaration int c = a+b; } } |
#7 What is an Object?
An instance of a class is called an object. The object has state and behavior.
Whenever the JVM reads the “new()” keyword then it will create an instance of that class.
Example:
public class Addition{ public static void main(String[] args){ Addition add = new Addition();//Object creation } } |
The above code creates the object for the Addition class.
#8 What are the OOPs concepts?
OOPs, concepts include:
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
- Interface
#9 What is Inheritance?
Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class. The existing class is known as the Superclass whereas the derived class is known as a Subclass.
Example:
Super class: public class Manipulation(){ } Sub class: public class Addition extends Manipulation(){ } |
Inheritance is only applicable to the public and protected members only. Private members can’t be inherited. This is the most important Core Java Interview Questions and Answers
#10 What is Encapsulation?
Purpose of Encapsulation:
- Protects the code from others.
- Code maintainability.
Example:
We are declaring ‘a’ as an integer variable and it should not be negative.
public class Addition(){ int a=5; } |
If someone changes the exact variable as “a = -5” then it is bad.
In order to overcome the problem we need to follow the steps below:
We can make the variable private or protected.
Use public accessor methods such as set<property> and get<property>.
So that the above code can be modified as:
public class Addition(){ private int a = 5; //Here the variable is marked as private } |
The code below shows the getter and setter.
Conditions can be provided while setting the variable.
get A(){ } set A(int a){ if(a>0){// Here condition is applied ……… } } |
For encapsulation, we need to make all the instance variables private and create a setter and getter for those variables. Which in turn will force others to call the setters rather than access the data directly.
#11 What is Polymorphism?
Polymorphism means many forms.
A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.
Example:
Public class Manipulation(){ //Superclass public void add(){ } } public class Addition extends Manipulation(){ // Subclass public void add(){ } public static void main(String args[]){ Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type addition.add(); } } |
Using the Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism. Polymorphism is applicable for overriding and not for overloading. This is the most important Core Java Interview Questions and Answers
#12 What is meant by Method Overriding?
Method overriding happens if the sub-class method satisfies the below conditions with the Super-class method:
- Method name should be the same
- The argument should be the same
- Return type should also be the same
- The key benefit of overriding is that the Sub-class can provide some specific information about that sub-class type than the super-class.
Example:
public class Manipulation{ //Super class public void add(){ ……………… } } Public class Addition extends Manipulation(){ Public void add(){ ……….. } Public static void main(String args[]){ Manipulation addition = new Addition(); //Polimorphism is applied addition.add(); // It calls the Sub class add() method } } |
addition.add() method calls the add() method in the Sub-class and not the parent class. So it overrides the Super-class method and is known as Method Overriding.
#13 What is meant by Overloading?
Method overloading happens for different classes or within the same class.
For method overloading, sub-class method should satisfy the below conditions with the Super-class method (or) methods in the same class itself:
Same method name
Different argument types
There may be different return types
Example:
public class Manipulation{ //Super class public void add(String name){ //String parameter ……………… } } Public class Addition extends Manipulation(){ Public void add(){//No Parameter ……….. } Public void add(int a){ //integer parameter } Public static void main(String args[]){ Addition addition = new Addition(); addition.add(); } } |
Here the add() method has different parameters in the Addition class is overloaded in the same class as with the super-class.
Note: Polymorphism is not applicable for method overloading.
#14 What is meant by Interface?
Multiple inheritances cannot be achieved in java. To overcome this problem the Interface concept is introduced.
An interface is a template which has only method declarations and not the method implementation.
Example:
Public abstract interface IManupulation{ //Interface declaration Public abstract void add();//method declaration public abstract void subtract(); } |
All the methods in the interface are internally public abstract void.
All the variables in the interface are internally public static final that is constants.
Classes can implement the interface and not extends.
The class which implements the interface should provide an implementation for all the methods declared in the interface.
public class Manupulation implements IManupulation{ //Manupulation class uses the interface Public void add(){ …………… } Public void subtract(){ ……………. } } |
#15 What is meant by Abstract class?
We can create the Abstract class by using the “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.
Abstract method:
The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations ends with a semicolon. This is the most important Core Java Interview Questions and Answers
Example:
public abstract class Manupulation{ public abstract void add();//Abstract method declaration Public void subtract(){ } } |
An abstract class may have a non- abstract method also.
The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.
#16 What is the difference between path and classpath variables?
PATH is an environment variable used by the operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable.
Classpath is specific to Java and used by java executables to locate class files. We can provide the classpath location while running java application and it can be a directory, ZIP files, JAR files, etc.
#17 What is the importance of main method in Java?
main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).
Java’s main method is public and static so that Java runtime can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program.
#18 Can we overload main method?
Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]). This is the most important Core Java Interview Questions and Answers
#19 Can we have multiple public classes in a java source file?
We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public.
#20 What is Java Package and which package is imported by default?
Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.
java.lang package is imported by default and we don’t need to import any class from this package explicitly.
#21 What are access modifiers?
Java provides access control through public, private and
protected access modifier keywords. When none of these are used, it’s called
default access modifier.
A java class can only have public or default access modifier
#22 What is final keyword?
The final keyword is used with Class to make sure no other class can extend it. For example, the String class is final and we can’t extend it.
We can use the final keyword with methods to make sure child classes can’t override it.
Java’s final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example, we can assign a final variable to an object only once but the object variables can change later on.
Java interface variables are by default final and static.
#23 What is static keyword?
static keyword can be used with class-level variables to make it global i.e all the objects will share the same variable.
static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.
#24 What is finally and finalize in java?
The finally block is used with try-catch to put the code that you want to get executed always, even if an exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes. This method gets called by the garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when the object is garbage collected.
#25 What are Loops in Java? What are three types of loops?
Ans: Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:
1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times. It is used when number of times to execute the statements is known to programmer.
2) While Loops
While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.
3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once.
#26 What’s the difference between an array and Vector?
Ans: An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.
#27 What is multi-threading?
Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.
#28 Why Runnable Interface is used in Java?
Ans: Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.
#29 What are the two ways of implementing multi-threading in Java?
Ans: Multi threaded applications can be developed in Java by using any of the following two methodologies:
1. By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented.
2. By writing a class that extend Java.Lang.Thread class.
#30 What is inner class in java?
We can define a class inside a class and they are called nested classes. Any non-static nested class is known as an inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them.
We can have local inner class or anonymous inner class inside a class. For more details read java inner class.
#31 What is anonymous inner class?
A local inner class without a name is known as an anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
#32 What is Classloader in Java?
Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method. Learn more at java classloader.
#33 What are different types of classloaders?
There are three types of built-in Class Loaders in Java:
Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
#34 What is ternary operator in java?
Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. An example can be found at java ternary operator.
#35 What does super keyword do?
The super keyword can be used to access the superclass method when you have overridden the method in the child class.
We can use the super keyword to invoke superclass constructors in child class constructor but in this case, it should be the first statement in the constructor method.
package com.journaldev.access;
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
public void test(){
System.out.println("super class test method");
}
}
Use of super keyword can be seen in below child class implementation.
package com.journaldev.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access super class method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}
#36 What is break and continue statement?
We can use break statement to terminate for, while, or do-while loop. We can use a break statement in the switch statement to exit the switch case. You can see the example of break statement at java break. We can use a break with the label to terminate the nested loops.
The continue statement skips the current iteration of a for, while or do-while loop. We can use the continue statement with the label to skip the current iteration of the outermost loop.
#37 What is this keyword?
this keyword provides the reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having the same name.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
#38 What is default constructor?
No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.
#39 Can we have try without catch block?
Yes, we can have try-finally statement and hence avoiding catch block.
#40 What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, the process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.
#41 What is meant by Exception?
An Exception is a problem that can occur during the normal flow of execution. A method can throw an exception when something wails at runtime. If that exception couldn’t be handled, then the execution gets terminated before it completes the task.
If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.
#41 Example for handling Exception:
try{ //Risky codes are surrounded by this block }catch(Exception e){ //Exceptions are caught in catch block } |
#42 What are the types of Exceptions?
There are two types of Exceptions. They are explained below in detail.
a) Checked Exception:
These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.
Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.
For Example, ClassNotFound Exception
b) Unchecked Exception:
These exceptions are not checked during the compile time by the compiler. The compiler doesn’t force to handle these exceptions. It includes:
Arithmetic Exception
ArrayIndexOutOfBounds Exception
#43 What are the different ways to handle exceptions?
Two different ways to handle exceptions are explained below:
a) Using try/catch:
The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.
Example:
class Manipulation{ public static void main(String[] args){ add(); } Public void add(){ try{ addition(); }catch(Exception e){ e.printStacktrace(); } } } |
b) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.
Example:
class Manipulation{ public static void main(String[] args){ add(); } public void add() throws Exception{ addition(); } } |
#44 What are the advantages of Exception handling?
The advantages are as follows:
The normal flow of the execution won’t be terminated if an exception gets handled
We can identify the problem by using catch declaration
#45 What are the Exception handling keywords in Java?
Enlisted below are the two Exception Handling Keywords:
a) try:
When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.
b) catch:
This is followed by a try block. Exceptions are caught here.
c) finally:
This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.
Check out the Latest Jobs for Java Developer: Link
Join WhatsApp and Telegram groups for daily job updates: Link
Prepare for Technical Round with Interview Questions: Link
Get insights into HR Interview Questions: Link
Craft a standout resume for Quick shortlisting: Link
Assessment with a Mock Test: Link
Mock Test with Aptitude and Coding Assessment: Click Here
Understand Recruitment Process, Test, and Exam Pattern: Link
Explore Global Opportunities for Professionals & Freshers Abroad: Link
TCS NQT 2023 Careers: Graduate Trainee Hiring: Link
PwC Internships 2023: Opportunities in Zurich, Switzerland: Link
Chandrayaan 3: India’s Upcoming Lunar Mission Expectations: Link