Core Java Interview Questions
Last updated on Jan 09, 2024
Java is a programming language released by the sun microsystems in 1995. It is a general-purpose language based on the concepts of object-oriented programming and the runtime environment(JRE) that consists of JVM, which is the cornerstone of the Java platform.
In this article, you can go through the set of Core Java interview questions most frequently asked in the interview panel. This will help you crack the interview as the topmost industry experts curate these at HKR training.
Most Frequently Asked Core Java Interview Questions
- What is object-oriented programming?
- What are the main uses of “this” keyword?
- How to achieve encapsulation in Java? Give an example
- What is object cloning?
- What is synchronization?
- What is the use of CallableStatement?
- Define Marker Interface
- How to apply pointers in a Java Program?
- Differentiate between JDK, JRE, and JVM
- What is meant by an Externalizable interface?
Let us have a quick review of the Core Java interview questions.
What is object-oriented programming? Is Java an object-oriented language?
Ans: Object-oriented programming works based on the concept of objects and the objects are the containers which store the data in the form of fields and code in the form of procedures which implements the logic for performing the operations. Java utilizes eight primitive data types such as boolean, byte, char, int, float, long, short, double and these data types are not the objects, hence java cannot be considered as a 100% object-oriented language.
What are wrapper classes in Java?
Ans: Wrapper classes convert the Java primitives into the reference types which are the objects. Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.
What is the difference between an Array list and vector in Java?
Ans:
Array List:
- It is not synchronized.
- It is fast and not it’s non-synchronized.
- The array size increases to 50% when an element is inserted into an Array List.
- It doesn’t define any increment size.
- It uses Iterator for traversing an Array List.
Vector:
- It is synchronized.
- It is slow and it is thread-safe.
- By default, the vectors will double the size of its array.
- It defines the increment size.
- It uses Enumeration as well as Iterator for traversing.
What is the output of the following Java program?
Ans:
class Test
{
public static void main (String args[])
{
System.out.println(10 + 20 + "Java");
System.out.println("Java" + 10 + 20);
}
}
The program prints the following output.
30Java
Java1020
In the first scenario, 10 and 20 will be treated as numbers and the sum operation is performed which displays 30. Now, this sum 30 is treated as a string and concatenated with a string Java. Hence, the output becomes “30Java”.
In the second scenario, the string Javatpoint is concatenated with 10 as string “Java10” which then again concatenates with 20 as “Java1020”
Explain the difference between ‘finally’ and ‘finalize’ in Java?
Ans:
Finally:
It is used along with a try-catch block, the “finally” block ensures that a particular piece of code is always executed, even if the execution is thrown by the try-catch block.
Finalize:
It is a special method in the object class. The finalize() method is generally overridden to release system resources when garbage value is collected from the object.
What are the main uses of “this” keyword?
Ans: There are many uses of this keyword.
- The keyword “this” can be used for referring to the current class instance variable.
- The keyword “this” can be used to invoke the current class method (implicitly).
- The method “this()” can be used to invoke the current class constructor.
- The keyword “this” can be passed as an argument in the method call.
- The keyword “this” can be passed as an argument in the constructor call.
- The keyword “this” can be used to return the current class instance from the method.
Become a Java Certified professional by learning this HKR Java Training !
Why is method overloading not possible by changing the return type in java?
Ans: It is not possible by changing the return type of the program due to avoid the ambiguity. The following example explains the ambiguity.
class Sum{
static int addition(int a,int b)
{
return a+b;
}
static double addition(int a,int b)
{
return a+b;
}
}
class TestOverloading3{
public static void main(String[] args)
{
System.out.println(Sum.addition(10,10));//ambiguity
}
}
Output:
Compile Time Error: method addition(int, int) is already defined in class Sum
What is the covariant return type?
Ans: From java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is a subclass type. This is known as a covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.
class A{
A get()
{
return this;
}
}
class B1 extends A{
B1 get()
{
return this;
}
void message()
{
System.out.println("welcome to covariant return type");
}
public static void main(String args[])
{
new B1().get().message();
}
}
Output:
welcome to covariant return type
Can you use this() and super() both in a constructor?
Ans: No. It’s because “this()” and “super()” has to be the first statement in the class constructor.
Example:
public class Test{
Test()
{
super();
this();
System.out.println("Test class object is created");
}
public static void main(String []args){
Test t = new Test();
}
}
Output:
Test.java:5: error: call to this must be first statement in constructor
. What is super in java?
Ans: The “super” keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever an instance of the subclass is created, an instance of the parent class is created implicitly which is then referred to by the super reference variable. The “super()” method is called in the class constructor implicitly by the compiler if there is no super or this.
Example:
class Fruit{
Fruit()
{
System.out.println("fruit is created");
}
}
class Apple extends Fruit{
Apple()
{
System.out.println("apple is created");
}
}
class TestSuper4{
public static void main(String args[])
{
Apple a=new Apple();
}
}
Output:
fruit is created
apple is created
. What are the differences between method Overloading and Overriding?
Ans:
Method Overloading:
- It increases the readability of the program.
- It occurs within a class.
- In this scenario, the parameters have to be different.
Method Overriding:
- It provides the specific implementation of the method that is already provided by its superclass.
- It occurs in two classes that have IS-A relationship between them.
- In this scenario, the parameters can be the same.
Core Java Certification Training
- Master Your Craft
- Lifetime LMS & Faculty Access
- 24/7 online expert support
- Real-world & Project Based Learning
. How to achieve encapsulation in Java? Give an example.
Ans: Apply these two steps for achieving encapsulation in java.
Declare the variable of the class as private.
Provide public set() and get() methods to modify the values of variables.
Example:
public class EncapsulationTest
{
private String empName;
private String empNum;
private int empAge;
public int getEmpAge()
{
return age;
}
public String getEmpName()
{
return name;
}
public String getEmpNum()
{
return empNum;
}
public void setEmpAge(int newAge)
{
age = newAge;
}
public void setEmpName(String newName)
{
name = newName;
}
public void setEmpNum(String newEmpNum)
{
empNum = newEmpNum;
}
}
. What is runtime polymorphism or dynamic method dispatch?
Ans
- In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
- In this process, an overridden method is called through the reference variable of a superclass.
Example:
class Bike {
void run()
{
System.out.println(“Bike is running”);
}
}
class Pulsar extends Bike {
void run()
{
System.out.println(“Pulsar is running safely with 100km”);
}
public static void main(String args[])
{
Bike b= new Bike(); //upcasting
b.run();
}
}
. What do you mean by an interface in Java?
Ans:
- An interface in Java is a blueprint of a class.
- It is a collection of abstract methods and static constants.
- Each method in an interface is public and abstract.
- Interfaces don’t contain any constructors.
- An interface is basically a group of related methods with empty bodies.
Example:
public interface Switch{
public void on();
public void off();
}
. What are the advantages of Packages in Java?
Ans: There are various advantages of packages in java.
- Packages avoid the name clashes.
- It provides easy access control.
- We can also have the hidden classes that are not visible outside and used by the package.
- It is easier to locate related classes.
. Why are Java Strings immutable in nature?
Ans: In Java, string objects are immutable which means once if the String object is created then its state cannot be changed. Java creates a new string object whenever you try to update the value of that object instead of updating the values of that particular object. String objects are generally cached in the String pool and hence Java String objects are immutable. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application.
. Can we change the scope of the overridden method in the subclass?
Ans: Yes. It is possible to change the scope of the overridden method in the subclass. However, it should be noticed that the accessibility of the method cannot be decreased. The following measures must be taken care of while changing the accessibility of the method.
- The private can be changed to protected, public, or default.
- The protected can be changed to public or default.
- The default can be changed to public.
- The public will always remain public.
. Can you modify the throws clause of the superclass method while overriding it in the subclass?
Ans: Yes, it is possible to modify the throws clause of the superclass method while overriding it in the subclass. However, there are certain rules that must be followed while overriding in case of exception handling.
- If the superclass method doesn’t declare an exception, then the subclass overridden method can’t declare the checked exception, but it can declare the unchecked exception.
- If the superclass method declares an exception, then the subclass overridden method can declare the same, subclass exception or no exception but it can’t declare parent exception.
. What is object cloning?
Ans:
- The object cloning is used for creating the exact copy of an object.
- The “clone()” method of the Object class is used to clone an object.
- The “java.lang.Cloneable” interface must be implemented by the class whose object clone has to be created.
- If the Cloneable interface is not implemented then the clone() method generates “CloneNotSupportedException”.
Example:
protected Object clone() throws CloneNotSupportedException
. Why is multiple inheritance not supported in java?
Ans: In order to reduce the complexity of the program and simplify the language, the concept of multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from a child class object, there will be ambiguity to call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit two classes. So whether you have the same method or different, there will be a compile-time error.
Example:
class A{
void message()
{
System.out.println("Hello");
}
}
class B{
void message()
{
System.out.println("Welcome");
}
}
class C extends A,B
{
//suppose if it were
Public Static void main(String args[])
{
C obj=new C();
obj.message();
//Now which message() method would be invoked?
}
}
Output:
Compile Time Error
. What is the difference between abstract classes and interfaces?
Ans:
Abstract class:
- An abstract class provides complete, default code and the details that must be overridden.
- In an abstract class, a class can extend only one abstract class.
- An abstract class can have non-abstract methods and instance variables.
- The visibility of an abstract class can be private, public or protected.
- The abstract class performs fast and it can use the constructors.
Interface:
- An interface doesn’t provide any code but only the signature.
- A class can implement several interfaces.
- All methods of an Interface are abstract and it doesn’t contain instance variables.
- The visibility of an interface can be either public or none.
- The interfaces will perform slow and it cannot use the constructors.
. What are the differences between Checked Exception and Unchecked Exception?
Ans:
Checked Exception:
- The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
- These exceptions are checked at compile-time.
Example: IOException, SQLException etc.
Unchecked Exception:
- The classes that extend “RuntimeException” are known as unchecked exceptions.
- These exceptions are not checked at compile-time.
Example: ArithmeticException, NullPointerException etc.
. What are the differences between processes and threads?
Ans:
Process:
- The process is an instance execution of a program.
- It uses inter-process communication to communicate with sibling processes.
- The changes which are made in the parent process doesn’t affect the child processes.
- Processes are controlled by the operating systems and it runs in separate memory spaces.
Thread:
- A thread is a subset of the process.
- Threads communicate directly with other threads of its process.
- The changes which are made in the main thread may affect the behaviour of the other threads of the process.
- Threads are controlled by the programmer in the program and it runs in shared memory spaces.
. What is synchronization?
Ans:
- Synchronization refers to multi-threading. A synchronized block of code is executed only by one thread at a time.
- Java supports execution of multiple threads, so two or more threads can access the same fields or objects.
- Synchronization is a process which keeps all concurrent threads in execution to be in sync.
- Synchronization avoids the memory consistency errors which are caused due to the inconsistent view of shared memory.
- When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.
. What is the difference between an Applet and a Java Application?
Ans:
Applets:
- These are executed within a java-enabled browser.
- It doesn’t require any main method to start the execution.
- It typically uses a restrictive security policy.
Java Application:
- As it is a standalone program, it can be executed outside of a browser.
- It requires a main method with a specific signature to start the execution.
- It uses more relaxed security policies.
. Explain the life cycle of an Applet?
Ans: An applet undergoes the following states during execution.
- Init: An applet is initialized each time is loaded.
- Start: Begin the execution of an applet.
- Stop: Stop the execution of an applet.
- Destroy: Perform a final cleanup, before unloading the applet.
. What is the difference between a Choice and a List?
Ans: A Choice is displayed in a compact form. In order to see the list of all available choices, the user must pull down the form. Choice allows only one item to select. A list is displayed in such a way that several List items are visible to the user. A list allows selecting one or more List items.
. What is the difference between a Scrollbar and a JScrollPane?
Ans: A Scrollbar is a Component, but not a Container whereas the ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
. What is the advantage of PreparedStatement over Statement?
Ans: The PreparedStatements are precompiled and so its performance is much better. This statement objects can also be reused with different input values to their queries.
. What is the use of CallableStatement?
Ans: A CallableStatement is used for executing the stored procedures. The stored procedures are stored and offered by a database. It takes the input values from the user and will return a result. The usage of stored procedures is highly recommended because it offers security and modularity. The syntax of a method that prepares a “CallableStatement” is the following:
Syntax:
CallableStament.prepareCall();
. State the various features of Java Programming
Ans. The following are the core features of Java Programming:
- Easy: Java is considered the easiest coding language to learn.
- Object-Oriented Programming: Java is an Object-Oriented Programming (OOP) language that denotes everything is viewed as an object.
- Independent Platform: Java is platform-independent and is not compiled into a platform-specific system. This language is assembled into platform-independent bytecode which is explained by the VMs (Virtual Machines) on which the platform runs.
- Secured Feature: This feature helps to develop a virus-free and damage-free system to make it available for users.
. Define ClassLoader?
Ans. A ClassLoader is a component of Java Virtual Machine (JVM) that helps in loading class files when a program is executed. Moreover, it is the first to load a workable file in Java language.
Top 30 frequently asked JAVA Interview Questions !
. Distinguish between C++ and Java languages.
Ans.
C++
- This is not a platform-independent language like Java.
- Moreover, C++ is also a programming language based on the C language. C++ is compatible with other high-level languages also.
- In C++ it's easy to access the native system libraries directly which represents a better platform for coding at the system levels.
- The source code is put together into an object code that is further performed to produce an output.
- This language separates itself with features similar to procedural and OOP languages.
- Moreover, the C++ language is only a compiled language.
Java
- Unlike C++, Java is incompatible with other higher-level languages.
- Java language is platform-independent because its compiler produces the byte code.
- Furthermore, Java can run on any system as its programs follow the “write once and run everywhere’’ concept.
- The native libraries in Java do not offer any direct call support. Users can use Java Native Interface (JNI) or access the libraries as they need.
- Unlike C++, Java programming is an interpreted & compiled coding language.
. What is found in the Java download file and what are their differences?
Ans. While downloading the Java file, we get the following two important things:-
JDK -
It refers to the Java Development Kit (JDK).
This is a dedicated kit only useful for developing software.
Further, it is Platform Dependent as the compiler generates the byte code.
The JDK package includes many tools useful for debugging and Developing.
JRE -
It refers to Java Runtime Environment (JRE) in Java.
JRE is a group of software and libraries designed for executing Java Programs.
This is similar to JDK in platform dependency.
The package supports various files and libraries for a runtime environment in Java language.
. Name the various Memory Allocations available in the Java language.
Ans. The following are the different types of memory allocations in Java.:-
- Class
- Stack
- Heap
- Native Method Stack
- Program Counter (PC) Memory
. What are the chances of running a program if we write a static public void main?
Ans. Yes, the program will run successfully even if we write such a keyword. This is due to the lack of specific rules for the order of specifiers in Java programming.
Subscribe to our YouTube channel to get new updates..!
. Define the default value that is stored in Local Variables.
Ans. There is no default value stored in either Local Variables or any primitives and Object references.
. Differentiate between Heap Memory and Stack Memory in Java?
Ans. Stack memory is useful to store the order of method execution and local variables. It is created at the time of the creation of threads. On the other hand, Heap memory is used to store the objects as dynamic memory for allocating the objects & JRE classes in the runtime.
. What is meant by an Association?
Ans. An Association is a relationship without having ownership over the other. You can understand this by an example, such as a person can have multiple bank accounts in different banks. And also, a bank can have multiple customers, but no one can own another’s.
. What is meant by Copy Constructor in Java?
Ans. This is a type of constructor in Java that builds an object through another object of the same class.
. Define the term “Aggregation”.
Ans. The aggregation is a relation or association between two classes and it is also described as a “whole/part” and “has-a” relationship. It helps in reusing the code in Java. It contains the reference object to another class or object and is said to have ownership of that class.
. Define Marker Interface.
Ans. An empty interface that doesn’t include any methods or constants in Java is a Marker interface. Popular examples of Market interfaces include Serializable, Cloneable, and Remote interfaces.
. Is Java language fully object-oriented?
Ans. No, Java language is not considered a 100% OOP language. This is because it still uses eight or more primitive data types such as int, float double, etc.
. What do you mean by an Object-Oriented Paradigm in Java?
Ans. It is a programming paradigm based on objects that aim to include the benefits of reusability & modularity. Further, it includes data and code where Data is in the form of fields and the regulation as procedures. Moreover, the object-oriented paradigm method allows us to build objects that perform together to generate better understandable software.
. What are the Wrapper Classes in Java programming?
Ans. In Java programming, Wrapper Classes offer the process to convert objects into primitive and vice versa.
. Define Object Cloning in Java.
Ans. The ability to create a similar object which is exactly the same is called Object Cloning. Java programming offers a method clone() useful to create a clone for an existing object. This object contains the same functionality as the original object.
. What is a Package in Java?
Ans. The package in Java is a collection of related classes, interfaces, important libraries, and JAR files. Moreover, they help in code reusability in Java.
. How to apply pointers in a Java Program?
Ans. Java Virtual Machine or JVM fully takes care of memory management in Java. The major aim of Java was to keep programming simple. Thus, memory access using pointers is not a recommended action in Java programming as it doesn’t allow any manipulation of the primary pointer through a reference variable. Thus, Java eliminates the concept of pointers.
. How will you differentiate Instance and Local variables in Java?
Ans. The instance variables are declared within a class but outside a method or a constructor.
But a local variable is a variable that can be anywhere inside a method or a constructor. Also, it has limited scope to the code segment where the variable is declared.
. What is meant by Java String Pool?
Ans. A Java String Pool is a group of strings within Java's Heap memory. Whenever you try to build a new string object, then the JVM checks the presence of the object within the pool. If it is available, the same object reference is shared with the variable, otherwise it will create a new object.
. Define JDK and its variants.
Ans. The term JDK stands for Java Development Kit which includes the Package of JRE and Developer tools useful for developing various Java Apps and Applets. It has three different variants:-
- Standard Edition
- Enterprise Edition
- Micro Edition
. Define the JIT compiler
Ans. JIT or Just-in-Time compiler is a runtime environment component that helps to improve the performance of Java apps. It helps to turn bytecode into machine code at runtime and then the same is executed directly.
. Define Access Specifiers and their different types.
Ans. Access Specifiers are predefined keywords used to set the access level to classes, methods, variables, etc. There are the following types of access specifiers in Java-
- Private
- Public
- Protected
- Default
. Differentiate between JDK, JRE, and JVM.
Ans.
JVM (Java Virtual Machine) includes a Just-in-Time (JIT) compiler tool that turns all the source code in Java into the low-level machine language (ML). It is very compatible to make it run faster than the constant application.
JRE or Java Runtime Environment includes class libraries and other JVM supporting files. But it doesn’t include any Java development tool like a compiler or debugger.
JDK or Java Development Kit includes some tools necessary to write Java Programs. Also, it uses JRE to execute these programs. Further, JRE contains a compiler, an applet viewer, and a Java app launcher.
. Does a construc Define the ‘This’ Java keyword.tor return a value in Java programming?
Yes, A constructor in Java can return a value where it returns the class's existing instance completely. But you cannot accurately make a constructor return a value.
. Define the ‘This’ Java keyword.
Ans. The term "this" is a specific keyword selected as a reference keyword and is useful to refer to the existing class properties. Such as method, variable, constructors, etc.
. What is meant by Method Overloading in Java?
Ans. This is a process of building multiple methods using the same name but they have different parameters. There are two ways to overload a method such as:
- Switching the number of arguments
- Changing arguments of data type
. What is called Late Binding?
Ans. Late binding is a dynamic binding process that occurs when the compiler doesn’t decide to call a method.
. Define the process of the life cycle of a thread.
Ans. The life cycle of a thread has five different states such as:-
- New Born
- Runnable
- Running
- Blocked
- Dead
. What is meant by an Externalizable interface?
Ans. In Java programming, the Externalizable interface helps to customize the serialization process. This interface includes two different methods such as- readExternal and writeExternal.
. Define in brief a JSP page.
Ans. JSP in Java refers to the Java Servlet Page is a text document that consists of two text types:-
- Static Data
- JSP Elements
. What is meant by JDBC?
Ans. JDBC refers to Java Database Connector which is an abstraction layer used to connect an existing database and a Java application.
Upcoming Core Java Certification Training Online classes
Batch starts on 10th Dec 2024 |
|
||
Batch starts on 14th Dec 2024 |
|
||
Batch starts on 18th Dec 2024 |
|