Whether you are preparing for interviews or looking to strengthen your Java skills, this blog will help you. I have curated this blog's mostly-asked Java interview questions and devised the perfect answers. Undoubtedly, this blog is the best platform to enhance your proficiency in Java concepts and programming. After reading this article, I am sure you will become a competent Java developer and gain a competitive edge in the job market.
Java has been a popular general-purpose programming language for more than 20 years. It has been a favourite programming language for developers and enterprises because it supports the development of a variety of robust software applications.
According to Oracle, Java runs on more than 60 billion JVMs worldwide. That’s why the demand for Java developers is soaring all the time. Keeping that in mind, I have compiled the top Java interview questions and answers to help Java aspirants crack their Java interviews easily. The interview questions cover crucial Java topics like classes, loops, objects, operators, OOP concepts, control statements, and constructors.
Additionally, I have given many example programs for many questions. It will help you to enhance your hands-on skills and make you job-ready.
Let’s jump in!
Table of Content - Java Interview Questions |
I have curated the various skills required for Java developers in this section. I have also added the job responsibilities of Java developers from entry-level to senior level.
Let’s go through them!
Here are the primary skills required for Java developers.
You can find the secondary skills required for Java developers in the following.
Below is the list of the job responsibilities of beginner-level Java developers.
The following are the job responsibilities of Java developers with middle-level experience.
Below are the job responsibilities of senior-level Java developers.
Okay! We have gone through the skills and responsibilities of Java developers. Next, we will dive into the Java interview questions straight.
In this section, I have developed the Java interview questions for beginners based on basic Java concepts. You will find questions from the Java version and features, classes, objects, variables, etc. It will undeniably help you get a strong foundation in Java concepts.
Let’s start now!
Java is an open-source, general-purpose, platform-independent language. It is an OOP-based language that we can use to develop web, IoT, gaming, big data, AI, mobile, and enterprise applications. Java was released by the company Sun Microsystems in 1995. Since then, it has been a reliable, secure platform for developers and enterprises.
Furthermore, Java is a fast, multi-platform, and versatile programming language. It is called WORA (Write Once and Run Anywhere) language since we can seamlessly write Java programs on any platform. That’s why Java is the right choice for developing cloud-based applications. Above all, Java offers a robust ecosystem with a rich set of libraries and in-built functions, allowing the development of various applications.
If you would like to become a Core Java Certified professional, then visit Mindmajix - A Global online training platform: "Core Java Training".This course will help you to achieve excellence in this domain. |
A small group of Sun Microsystems engineers, the ' Green Team' led by James Gosling, invented the Java language. They introduced Java to the world in 1995. Java continues to be one of the top-ranked programming languages. Developers and Enterprises use Java to build a range of applications.
Initially, the language was designed to develop embedded systems for use in electronic appliances. The initial names of Java are ‘Greentalk’ and ‘Oak’. Then, it got the name Java, which refers to an island in Indonesia where coffee was first invented.
The latest version of Java is Java 22 or JDK22. This version was released on March 19, 2024. JDK 21 is the latest Long-Term Support (LTS) release of the Java SE platform on September 19, 2023. JDK 21 replaced JDK 17, the earlier LTS of the Java SE platform.
The latest Java version, JDK 22, has many new features and capabilities. Below are some of the key features of the JDK 22.
JDK 22 is the long-term support release, whereas JDK 21 is the short-term support release.
Java is the first programming language to write virtual machine code. That's why Java is called JVM (Java Virtual Machine). It also provides a new feature called code reusability.
Java |
C++ |
Java is platform-independent | C++ is platform-dependent |
It supports the Go-to statement | It supports the go-to statement |
It doesn’t support structures and unions | It does support unions and structures |
It has built-in support for threading | It does not support threading |
We use Java for building applications | We use this language for system programming |
Java uses both an interpreter and a compiler | C++ uses compiler only |
The following are the key features of Java:
A class in Java is a blueprint that supports the creation of individual objects. We can use classes to define object data types and methods. We can consider classes as categories and objects as items of the categories. The important thing is that all the class objects must have the class properties.
Main.java
- public class Main {
int x = 5;
-public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
An example of a Java class is shown below.
In Java, we refer to an instance of a class as an object. Every object in Java has both state and behavior. To understand objects better, consider a real-time object – a bicycle. A bicycle has states like current gear, speed, pedal cadence, etc. Similarly, a bicycle can have behaviors like applying brakes, changing gears, etc.
Code:
Main.java
class elearning
- {
public static void main(String args[])
- {
System.out.println("MindMajix");
}
}
Output:
java -cp /tmp/YG7EbOTmWS/elearning
MindMajix
=== Code Execution Successful ===
JVM stands for the Java Virtual Machine. JVM is a part of JRE (Java Runtime Environment. It is a virtual machine that provides a runtime environment to write Java codes. We use JVM to execute Java bytecodes.
The JVM acts as an interpreter between Java and the underlying hardware. It allows Java applications to run on different operating systems and platforms. The main thing is that JVM plays a crucial role in memory management through automatic memory allocation and garbage collection.
The memory in the JVM is divided into five areas. They are:
A class loader dynamically loads Java classes into the JVM during the execution. Data will be loaded from the Classloader first whenever we run Java programs. A class loader is one of the components of the JRE. The JVM doesn’t need underlying files to run Java programs.
There are three class loaders in JVM in total. They are:
Java Development Kit, or JDK, is one of the three technology packages used in Java programming. We use JDK to implement Java platform specifications such as class libraries and compilers. With JDK, we can develop software applications and applets.
JDK is a platform-specific component that contains the Java interpreter, Java compiler, Java classes, and development tools. JDK is the core package of Java, also known as the superset of the JRE.
Java Runtime Environment, or JRE, is one of the three Java platform components besides JVM and JDK. JRE is a collection of software tools that support developing high-performance Java applications. Though JRE is a part of JDK, we can download it separately.
JRE enables communication between Java programs and the operating system. It acts as a facilitator, offering all the required resources to developers. So, developers can run applications on any operating system without any customisation.
Just-In-Time Compiler or JIT is one of the critical components of JRE. JIT compiles the bytecodes of a particular method into the native machine code at runtime. In a way, the JIT compiler helps to improve the performance of Java applications.
When a method is compiled, the compiled code is directly called by the JVM without interpretation. The important thing is that the compilation doesn’t require a processor and memory, which speeds up program compilation.
Variables in Java are the basic storage units that hold data values. We can access and modify these values. Variables are the memory locations where we can store values. We need to declare all variables before using them. Also, we can assign a variable with a data type such as a number, string, character, etc.
The syntax for a variable is given as below:
type variableName = value;
type – It can be an integer or string
variableName – The name of the variable
Value – The value assigned to the variable
An example of a variable is given below.
int mynumber = 10;
There are three main variables available in Java. They are:
Static Variables: A variable declared with the static keyword is called a static variable. A static variable cannot be a local variable. We can allocate memory only once for these variables.
Instance Variables: an instance variable declared inside the class but outside the body of a method. An instance variable is instance-specific. So, we cannot share instance variables.
Local Variables: A variable declared inside a method's body within a class is called a local variable.
Example:
class A
-{
int num-30;//instance variable
static char name=MindMajix;//static variable
void method()
- {
int n=90;//local variable
}
}//end of class
We use type casting in Java to convert one data type into another. The casting operator can perform typecasting while designing a Java program.
There are two types of typecasting, as listed below.
The below flow diagram shows the conversions.
Datatypes in Java specify the values and sizes we can store in variables. The data type informs the compiler how to handle a variable or method.
There are two types of data types in Java. They are:
Primitive Data Type | Default Size | Default Value |
Integer | 4 bytes | 0 |
Character | 2 bytes | ‘u0000’ |
Byte | 1 byte | 0 |
Short | 2 bytes | 0 |
Long | 8 bytes | 0L |
Floating point numbers | 4 bytes | 0.0f |
Double | 8 bytes | 0.0d |
Boolean | 1 bit | False |
We need to use the new keyword to create an object in Java. The syntax for the object creation is given below.
ClassName objectName = new ClassName();
ClassName – The name of the class where the object is created
objectName – The name of the object created.
An example of object creation is given below.
// creating an object for MindMajix
MindMajix m1 = new MindMajix();
Unicode is a Universal International Standard Character Encoding system. All the written programming languages comply with this unicode system worldwide. The hexadecimal number is used to represent characters in the Unicode system. For example, the value 0x0041 in the Unicode system represents the Latin character A.
Java supports the Unicode system and represents characters with a 16-bit data type. The characters in hexadecimal numbers range from 0x0000 to 0xFFFF. At the same time, characters that are larger than 16 bits are called supplementary characters. They range from 0x10000 to 0x10FFFF.
Java compiler converts source codes into bytecodes. Generally, bytecodes are platform-independent, so we can compile and execute them on any platform.
No, they are not Java keywords.
Nothing changes. The compilation and execution of programs will occur properly since the order of specifiers doesn’t matter in Java.
No, there is no default value for a local variable in Java. So, we must assign values for local variables before compilation. Otherwise, the compiler will throw an error.
Java supports eight types of operators. They are:
1. Arithmetic operators
2. Logical operators
3. Assignment operators
4. Relational operators
5. Unary operators
6. Bitwise operators
7. The ternary or conditional operator
8. Instanceof operator
Java provides a set of rules and regulations to specify how to execute operators. If an expression has many operators, then the execution of the expression is done based on the operator precedence.
This operator precedence evaluates the operators based on the priority. For example, multiplication has the highest priority over addition and subtraction.
The J2EE design patterns are a set of practices that help to solve recurring design problems. Design patterns are ready-made solutions to solve different issues. Java offers various design patterns, such as MVC, data transfer objects, session facades, and business delegates.
The MVC pattern is automatically chosen when we choose a web application template in the workspace. The session façade design pattern reduces complex interactions between lower-level EJBs. The data transfer object provides enhanced reusability and maintainability. The business delegate design pattern separates clients and business services to hide implementation details of business services.
Operator | Description |
Logical NOT |
|
Logical OR |
|
Logical AND |
|
The unary operator in Java has only one operand. It performs various operations, including negating an expression, incrementing or decrementing a value by one, etc.
An example of the unary operator is given below:
Code:
Main.java
class UnaryExample
- {
public static void main(String args[])
- {
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
Output:
java -cp /tmp/nRpgsmRLTQ/UnaryExample
=== Code Execution Successful ===
If the subclass in a Java program has the same method as declared in the superclass, it is known as method overriding. It allows the subclass to customise the method's behaviour without impacting the parent class.
When you want to override a method, you need to use the @override annotation. It tells the compiler that we want to override a method in the superclass. Method overriding provides better reusability of codes and extensibility of functionalities. It makes codes modular and maintainable.
Below is an example showing the use of method overriding.
Main.java
▾ class Animal {
▾ public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
▾public void displayInfo() {
System.out.println("I am a dog.");
}
}
▾class Main {
▾public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
We use the super keyword to invoke the overridden method if the method overrides one of the superclass’s methods. We also call the super keyword a reference variable that helps to refer to the immediate superclass of a class. We can apply the super keyword to access the elements of the superclass from within the subclass.
Consider the superclass and subclass below and see how the super keyword invokes the overridden method.
public class Superclass {
public void printMethod() {}
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
If a Java class has multiple methods with the same name and different parameters, we call it method overloading. The main advantage of method overloading is that it increases the readability of a Java program.
Method overloading also supports reducing code duplication. So developers can write a single method for multiple purposes. For example, you can apply the add method to add integers, floating point numbers, and so on. Besides, it improves flexibility by allowing different arguments in a single method.
The example below shows the use of method overloading in Java.
Code:
class MethodOverloading {
private static void display(int ,a){
System.out.println("Arguments:+ a);
}
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[ ] args) {
display(2);
display(3, 6);
}
}
Output:
java -cp /tmp/aZdRq9gbSx/MethodOverloading
Arguments: 2
Arguments: 3 and 6
=== Code Execution Successful ===
In Java, the package is typically a collection of classes and interfaces bundled together and related to each other. Packages in a program help developers group the code to increase reusability. We can use packages by importing them into different classes.
We use packages to eliminate name conflicts. We can also organise codes into logical units using packages. There are two types of Java packages: built-in and user-defined. We can use the package keyword to create packages in Java.
Here is an example of using the package keyword.
package mypack;
We can define a singleton class as a class that consists of only one instance. In this class, all methods and variables belong to only one instance. We use a singleton class to limit objects for a class.
A singleton class, a private static instance variable along with a private constructor. We can use the single instance of a singleton class throughout the lifecycle of a software program.
The primary use of the ‘this’ keyword is to refer to the current object in a Java program.
Spring Boot is a Java-based tool that we use to develop Microservices and web applications. It is also an extension built on the Spring framework. We use Spring Boot to create high-quality web applications, reducing development time significantly.
Major companies like Uber, Netflix, and Airbnb use Spring Boot to develop their applications because Spring Boot helps to create standalone applications and improve productivity.
The following are the uses of this keyword in Java. They are:
An object class is the superclass for all the classes in Java.
Sure! This section might have strengthened your basics of Java concepts. It will help you learn advanced Java concepts effortlessly.
In this section, I have prepared the Java interview questions and answers for learners who wish to explore further Java concepts. You will gain a comprehensive knowledge of Java by reading through this part of the article.
Let’s go ahead!
The following are the key differences between C and Java languages.
C language | Java |
C is a Procedural-Oriented language | Java is an Object-Oriented programming language. |
Functions play a crucial role in C. | Objects play a vital role in Java. |
It is an intermediate-level coding language. | It is a high-level coding language. |
It does not support OOP Concepts. | Java supports OOP concepts |
We can use the malloc() keyword for memory allocation. | We can use the new keyword for memory allocation. |
It doesn’t support the threading concept. | Java supports threading |
It is not a portable language | It is a portable language |
Default members of C are public | Default members of Java are private |
C supports storage classes. | Java doesn’t support storage classes. |
++a is a prefix increment operator, whereas a++ is a postfix increment operator. The prefix increment operator returns the value ‘a’ after incrementing it. The postfix increment operator returns the ‘a’ value before incrementing it.
The below example shows the use of the operators.
Code:
class HelloWorld {
public static void main(String args[ ])
int a, b;
// Pre-increment
a = 1;
b = ++a;
System.out.println( b );// prints 2
// Post-increment
a = 1;
b = a++;
System.out.println( b );// prints 1
}
}
Result:
java -cp /tmp/dbMsHKUKUr/HelloWorld
=== Code Execution Successful ===
JVM | JDK | JRE |
It stands for Java Virtual Machine | It stands for Java Development Kit | It stands for Java Runtime Environment |
It is the heart of Java programming. | It is a development platform and the superset of the JRE. | We use JRE for code execution |
It executes programs line by line | It has the JVM | It has the JVM |
It converts bytecodes into machine codes. | It provides executables, tools, and binaries | It contains Java classes, binaries, and JVM. |
Left Shift: The left shift is a bitwise operator in Java. In this shift, bits are moved towards the left-hand side, and zeros are placed at the rightmost places.
The example below shows the left shift.
Code:
public class LeftShiftOperator {
public static void main(String[] args)
int a=2;//
int i;
i=a<<1;//4
System.out.println("the value of a before left
shift is: " +a);
System.out.println("the value of a after applying
left shift is: " +i);
}
}
Output:
java -cp /tmp/GIYi18A02D/LeftShiftOperator
the value of a before left shift is: 2
the value of a after applying left shift is: 4
=== Code Execution Successful ===|
Right Shift: The right shift is also the bitwise operator in Java. In this shift, bits are moved towards the right-hand side, and zeros are placed at the leftmost place.
The example below shows the right shift.
Code:
public class RightShiftOperator {
public static void main(String[] args) {
int a=2;
int I;
i=a>>1;
System.out.println("the value of a before right shift is:
" +a);
System.out.println("the value of a after applying right
Output:
java -cp /tmp/xy76CaCCuR/RightShiftOperator
the value of a before right shift is: 2
the value of a after applying right shift is: 1
=== Code Execution Successful ===
We use bitwise operators in Java to perform bit operations.
The following are the bitwise operators in Java. They are:
We use the ternary operator in Java to replace the if-else statement. It is also known as the conditional operator that uses three operands.
The syntax for the ternary operator is given as:
variable = (expression)? expression true:expression false
The example below shows the use of the ternary operator.
int age = 21;
String result = (age 18) ? "adult" : "minor";
In Java, every character is represented by 2 bytes. The notation ‘u0000’ is the lowest range of the Unicode system. The notation ‘uFFFF’ is the highest range of the Unicode system. Also, it is the default value of the character data type.
Yes, an empty Java file is a valid source file name. But we cannot run an empty file since it has no codes. Java allows saving Java files by using the .java extension. We must compile the files using the javac .java command and run them using their class name.
Java keywords, called "Reserved keywords, " act as a code key. Keywords in Java are predefined. We cannot use a Java keyword as an object name, variable, or identifier in Java programs.
Java offers nearly 50 keywords, including abstract, default, break, new, extend, static, import, etc. Though true, false, and null seem like keywords, they are literal.
Java has four access specifiers. They are:
1. Private: We can access the methods or classes declared private within the same class.
2. Public: We can access the methods or classes declared public anywhere in a program. In other words, we can access them within and outside the class.
3. Default: By default, all the variables, classes, and methods are of default scope. The default is accessible only within the package.
4. Protected: We can access the methods, variables, and classes defined as private within the same class of the same package or by the subclass of the same class.
By using packages in Java, we can:
The program is given as follows:
Code:
class Java
{
public static void main (String args[ ])
{
System.out.println(10 * 20 + "MindMajix");
Output:
java -cp /tmp/tKdYXDrlIn/Java
200MindMajix
MindMajix200
=== Code Execution Successful ===
Control statements are divided into three types in Java. They are:
Selection statements are also called conditional or branching statements. We can use the selection statement to control the execution flow of a Java program. It allows Java programs to make decisions based on conditions. Once the condition is satisfied, they direct the program to follow a certain path. If not, they direct the program to follow another path.
Selection/Conditional statements in Java include:
The iterative statements in Java are also called looping statements. They are a set of statements that we can run repeatedly until the condition for the termination is not met.
Looping/iterative statements in Java include:
We use Jump statements in Java to transfer control to another part of a program based on a condition. Also, we use these statements to jump directly to other statements.
The jump statements used in Java are break, continue, and return.
The ‘For-Each’ loop is an array traversing technique used in Java, such as for and while loops. We use this loop to iterate over a collection or array-like ArrayList.
An example of a ‘For-Each’ loop is given as follows:
Code:
class ForEachPro{
public static void main(String args[ ]){
//declaring an array
int arr[ ]={21, 22, 23, 24};
//traversing the array with for-each loop
Output:
java -cp /tmp/FD2FPUTNPJ/F8rEachpro
When it comes to the while loop, we test the condition first. If the condition is true, then the loop continues. If not, execution is stopped.
When it comes to the do-while loop, we execute the condition first. We test the condition at the end of the loop.
The syntax for the while loop is given as follows:
while(condition){
//code to be executed
}
The syntax for the do-while loop is given as follows:
do {
//code to be executed /
//update statement
}while (condition);
Java comments are statements that are not executed by the compiler and interpreter. We use comments to provide information about the class, methods, variables, and statements. Moreover, we use them to hide program code for a specific time.
There are three types of comments in Java. They are:
OOP is the short form for Object-Oriented Programming Language.
Simula is the first object-oriented programming language. The most popular OOP languages are Java, PHP, C++, Python, and many more.
The following are the OOP concepts used in Java:
Abstraction is an OOP concept that hides unnecessary data and only shows necessary data to users. In other words, abstraction hides internal processes and indicates only the functionalities of an application.
Encapsulation is an OOP property that binds data and code into a single unit.
According to the inheritance property, a child class object can acquire the properties of its parent class. We apply inheritance to acquire runtime polymorphism and also provide code reusability.
Polymorphism in Java provides a way to perform one task in different possible ways. We use method overriding and method overloading to achieve polymorphism in Java.
The following are the advantages of OOP concepts. They are:
Object-oriented programming language supports all the features of OOP concepts. Examples of object-oriented programming languages are Python and Java.
An object-based programming language supports the features of OOP concepts except inheritance. JavaScript and VBScript are some examples of Object-based programming languages.
All the object references in Java are initialised to null.
The object-oriented paradigm depends on objects that have defined methods in the class. We use this paradigm to incorporate code reusability and modularity. Objects are defined as instances of classes that interact with one another to design programs and applications.
The features of the object-oriented paradigm are given as follows:
Java naming convention is a rule that we follow to name identifiers such as packages, methods, variables, and constants. Many Java communities, such as Sun Microsystems and Netscape, support these conventions. All the fields of Java programming are given Java naming conventions.
The rules that we must follow to declare a class are given as follows:
An example of the class is given below.
public class Thread
{
//code
}
A constructor is a special type of method with a block of code to initialize the state of an object. A constructor is called when the instance of the object is created. Similarly, a constructor is called when a Java object is created using the new keyword.
We need to follow the rules below:
Java has two types of constructors. They are:
Parameterized constructor: A parameterized constructor is another constructor used to initialize instance variables with the given values. A parameterized constructor is a constructor that accepts arguments.
Default constructor: We call a default constructor as a no-argument constructor. We use this constructor to initialize an instance variable with a default value. Moreover, we use this constructor to perform some useful tasks in object creation. The compiler implicitly invokes the default constructor if no constructor exists for a particular class.
An example of a default constructor is as follows:
Code:
// Java Program to create and call a default constructor
class MindMajix1{
//creating a default constructor
MindMajix1()
{
System.out.println("Welcome to MindMajix");
}
//main method
public static void main(String args[]){
//calling a default constructor
MindMajix1 m=new MindMajix1();
}
}
Output:
java -cp /tmp/UHJIOYInbH/MindMajix1
Welcome to MindMajix
=== Code Execution Successful ===
An example of a parameterized constructor is as follows:
Code:
class Student{
int id;
String name;
//creating a parameterized constructor
Student (int i, String n){
id = i;
name = n;
}
//method to display the values
void display() { System.out.println(id+" "+name); }
public static void main(String args[]){
//creating objects and passing values
Student s1 = new Student (111,"Mind");
Student s2 = new Student (222, "Majix");
//calling method to display the values of object
s1.display();
s2.display();
}
}
output:
java -cp /tmp/lyrufeqn7m/Student
111 Mind
222 Majix
=== Code Execution Successful ===|
A Java constructor will return the class's current or present instance.
No, a constructor in Java cannot be inherited.
Yes, it is possible to overload a constructor by changing the number of arguments for each constructor in a particular program. It is also possible to overload a constructor by changing the parameter data types.
No, we cannot declare a constructor as final. If we declare a constructor as final, the compiler will throw a "modified final not allowed" error.
Yes, the constructor class is available in Java. The purpose of the constructor class is to get the constructor's internal information. The information is available in the Java.lang.reflect package.
There is no copy constructor in Java.
Java allows the copying of values of one object to another in the following ways:
In Java, we can define a method as a set of codes represented by a name. Using a method's name, we can invoke the method at any point in a program. Every method in a program has its own name, which is not the same as that of a class name.
Good! This section might have enhanced your expertise in Java to the next level. You have gained solid knowledge of constructors, OOP concepts, Java methods, and more from this section.
In this section, I have created Java interview questions and answers from advanced Java concepts, elevating your expertise in Java to greater heights.
Let’s move on!
Object-Oriented Design (ODD) is a process of using Object-Oriented methodology to develop software applications. In other words, it is a part of the object-oriented programming process. ODD supports the design of the system architecture after the object-oriented analysis (OAA) is made.
The output of OOA, such as the conceptual systems model, user interface, system rational model, etc., are given as input to the OOD process. These inputs help to identify relationships and design systems classes and objects, interfaces, etc.
Both JAS RS and JAS WS are Java APIs that we use to develop web services. JAS WS or Jakarta XML web services is an API with which we can create SOAP web services that interact with XML. Besides, it allows developers to build RPC-oriented and message-oriented web services.
JAS RS or Jakarta RESTful web services is an API with which we can create Java web services using the REST architectural style. This API provides declarative annotations to identify components of applications, extract data, route requests, and provide metadata.
The common convention for Spring converter-type classes is to use suffixes before a converter. For example, StringConverter is a converter that converts a string into an integer. Note that a converter class must implement the converter interface.
Java Spring also provides built-in converters to convert the basic types such as string, Boolean, integer, etc. Additionally, Java provides a solid type conversion SPI for creating custom converters.
An example of a Spring converter class is given below.
public class StringConverter implements Converter<String, Integer> {
}
@Override
public Integer convert(String source) {
return Integer.parseInt(source);
}
@Override
public boolean canConvert (Class<?> targetType) {
return targetType == Integer.class;
}
}
We can use this converter type to convert a string into an integer. We need to call the convert() method for this conversion.
Checked Exceptions | Unchecked Exceptions |
These exceptions occur at the compile time. | These exceptions arise at the run time. |
They are the subclass of the exception class | They are not part of the exception class |
Compilers check these exceptions | Compilers don’t check these exceptions |
We catch these exceptions during the compile time. | We cannot catch these exceptions during the compile time. |
The JVM needs these exceptions to catch and hold. | The JVM doesn’t need these exceptions to catch and hold. |
We can achieve abstraction in two ways in Java.
Interfaces achieve complete abstraction. They can contain only abstract methods and constant declarations.
Abstract classes achieve partial abstraction. We cannot instantiate abstract classes. We can use them as base classes for other classes.
ArrayList | Vector |
It is not synchronized, so it is fast. | It is synchronized, so it is slow. |
Multiple threads can access ArrayList at a time | Only one vector can access a vector at a time. |
It increments by 50 % of the array size when the number of elements increases its capacity. | It increments by 100% of the array size when the number of elements increases. |
It uses the iterator interface to traverse elements | It uses both an iterator and enumeration interface to traverse elements |
It is not a legacy class | It is a legacy class. |
We use the equals () method to compare the equality of two objects. We can compare equality in two ways: shallow comparison and deep comparison.
The syntax for the equals () method is given as follows.
public boolean equals (objects obj)
We use the hashCode () method to return the hashcode value. The value is returned as an integer. We use the hashcode value in hashing-based collections such as HashMap, HashTable, HashSet, etc.
The syntax for the hashCode () method is given below.
public int hashCode()
The differences between the constructor and method are given as follows:
Constructor | Method |
A constructor should have the same name as the class name | A method name is not the same as that of a class name |
A constructor has no return type | A method must have a return type |
It can be invoked implicitly | It can be invoked explicitly |
We can use a constructor to initialize the state of the object | We can use a method to expose the behavior of an object. |
Java compiler provides the Default constructor | Java compiler doesn’t provide the default method. |
In Java, a method signature is a specified format followed by a method with its type, name, and order of parameters. Exceptions are not considered a part of a method signature.
An example of a method signature is given below.
return-type method name (parameter list)
{
//code
}
We use static keywords to manage memory. We can declare block, method, variable, and nested classes as static.
In Java, we can declare a variable as static. When we do so, we must ensure that the following rules are satisfied. They are:
An example of a static variable is given as follows:
Code:
class Student{
}
int rollno;//instance variable
String name;
static String training ="MindMajix";//static variable
Student (int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+"
+training);}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student (111, "Ram");
Student s2 = new Student (222, "Kareem");
s1.display();
s2.display();
}
}
Output:
java -cp /tmp/UMrGH30Zbe/TestStaticVariable1
111 Ram MindMajix
222 Kareem MindMajix
=== Code Execution Successful ===
If we declare a method as static, the following operations take place. They are:
The restrictions that we encounter are:
The main reason is that we don't need an object to call for a static method. If we declare the main() method non-static, we must create an object first. Only then can we call the main () method. That’s why we declare the main() method static to save memory.
No, we cannot override the static method in Java.
We use a Static block in Java to initialise the static data members. It is executed before the main method is executed during class loading.
An example of a static block is given as follows:
Code:
Class Mindmajix{
static { System.out.println("static block"
public static void main(String args[]){
System.out.println("Hello World");
}
}
Output:
static block
Hello World
Using a static block, we can execute a Java program without the main() method. However, it is possible only for the JDK 1.6 version. Executing a Java program without the main() method from the JDK 1.7 version is not supported.
The program will be compiled. But it throws a NoSuchMethodError error at runtime.
The static context is suitable for only variable, class, and method - not for the object. Constructors are usually invoked when an object is created. So, we can't declare a constructor as static in Java.
No. If we declare abstract methods static, they become part of the class. Therefore, declaring an abstract method static is not allowed.
Yes, we can. There is no need for an object to access the static block. Therefore, we can access static methods and variables declared inside the abstract class by using the name.
Consider the following example.
Code:
abstract class Check
{
static int i = 100;
static void CheckMethod()
{
System.out.println("MindMajix");
}
}
public class CheckClass extends Check
{
public static void main (String args[])
{
Check. CheckMethod();
System.out.println("i = "+Check.i);
}
}
Output:
java -cp /tmp/2XCeCLt7vL/CheckClass
MindMajix
i = 100
=== Code Execution Successful ===
Yes, this keyword refers to the current class instance variable. We use this keyword to initiate or invoke the current class constructor.
The syntax for inheritance in Java is as follows:
class Superclass extends subclass
{
//code
}
Using the Math. random() method, we can generate random numbers in Java ranging from 0.1 to less than 1.0. Moreover, we can generate the random numbers using the Random class in Java.util package.
Java's main() method doesn't return any data because we declare it with a void return type.
Java doesn’t support multiple inheritances to reduce the complexity.
If we apply multiple inheritance in a Java program, the result will be as follows:
Code:
class X{
void msg()
{
System.out.println("Hello");}
}
class Y{
void msg()
{
System.out.println("Welcome"); }
}
class Z extends X,Y{//suppose if it were
public static void main(String args[]){
Z obj=new Z();
}
}
obj.msg(); //Now which msg() method would be invoked?
Output:
ERROR!
/tmp/xdn0K4y85E/X.java:11: error: '{' expected
class Z extends X,Y{//suppose if it were
1 error
=== Code Exited With Errors ===
Java's main() method must be public static to run any program. If we declare the main () method as private, there will be no complications. But the method will throw a runtime error.
Yes, Java classes can have multiple constructors with different parameters.
There are two different ways to overload a method. They are:
Below is an example of a Java program that uses the method overloading by changing the data types.
Code:
class MethodOverloading {
private static void display(int a){
}
System.out.println("Got Integer data.");
private static void display(String a){
}
System.out.println("Got String object.");
public static void main(String[] args) {
display(1);
display("Hello");
}
}
Output:
java -cp /tmp/QHf3014Szm/MethodOverloading
Got Integer data.
Got String object.
=== Code Execution Successful ===
Below is an example of a Java program that uses the method overloading by changing the data types.
Code:
class MethodOverloading {
private static void display(int a){
}
System.out.println("Arguments: " + a);
private static void display(int a, int b){
}
System.out.println("Arguments:+ a +and+ b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}
Output:
java -cp /tmp/EGHKFTF4P3/MethodOverloading
Arguments: 1
Arguments: 1 and 4
=== Code Execution Successful ===
Ambiguity is the reason why method overloading is not supported in Java by changing the method's return type.
It is possible to overload the main() method using method overloading. However, JVM only calls the main() method, which receives string arrays as arguments.
We use method overriding to achieve runtime polymorphism. We also use method overriding to provide a specific implementation for a method given by its subclass.
We need to follow the rules below during method overriding:
Code:
class Shape{
void run()
{
System.out.println("Shape is ready");
}
}
class Rectangle extends Shape{
{
}
void run()
System.out.println("Rectangle is drawn");
public static void main(String args[]){
Rectangle obj = new Rectangle();//creating object
obj.run(); //calling method
}
}
Output:
java -cp /tmp/Joi65Hfvhs/Shape
Rectangle is drawn
No, we cannot override a static method. A class bounds a static method, whereas an object bounds an instance method. Moreover, a static method belongs to the class area, whereas an instance method belongs to the heap area.
No, we cannot override a main () method in Java since the main () method is static.
Aggregation in Java is built to represent a weak relationship. But, the composition is built to represent a strong relationship.
A pointer is a variable that refers to the memory address. Java doesn’t support pointers because they are complex and insecure.
The uses of the super keyword in Java are given as follows:
Yes, all the functions in Java are virtual by default.
Cheers! You have completed learning Java interview questions and answers. Now, you are ready for Java interviews. Undoubtedly, you will crack your interviews and land your dream job.
Yes, learning Java is easy. Learning the fundamentals of Java is easy and fun. You only need strong determination, hard work, and effort to learn Java. Java has many advantages, such as vast community support and open-source language so that you can get support from many sides. MindMajix offers Java training with industry-experienced trainers and a comprehensive course curriculum. No doubt learning Java is a piece of cake in MindMajix.
Developers and enterprises leverage Java to build mobile, web, and desktop GUI applications. That’s why it has been one of the high-demand programming languages for more than two decades. AmbitionBox says Java developers get an average annual salary of 6 Lakhs in India. According to Glassdoor, the average annual package for Java developers in the USA is 124k USD. From these key figures, you can understand that learning Java is promising and rewarding.
According to Glassdoor, top companies such as TCS, Accenture, CTS, Capgemini, Wipro, Virtusa, and Tech Mahindra hire Java developers in large numbers with fantastic salary packages.
Java is suitable for AI since it is a robust, versatile coding language with a large user community. Also, it offers better security, reliability, and scalability. Also, Java is platform-independent. So you can run Java applications on any platform. Java has many libraries for NLP, machine learning, etc. Some AI applications built based on Java are Netflix, Google Search, and IBM Watson.
For beginners, it may take 2-4 months to learn Java. For experienced learners, it may take 1-2 months. Mindmajix offers 25 hours of core Java training in live online and self-paced video modes. You will learn core Java in 25 hours if you choose live online mode. If you prefer self-paced videos and watch two videos per day, you will learn core Java in 13 days.
All right! You have gone through the key Java interview questions and answers in this blog. This article must have enhanced your knowledge of Java concepts. The example Java programs in this blog must have elevated your hands-on skills to new heights. However, if you go through professional Java training, it will boost your Java knowledge and skills dramatically.
MindMajix is the leading eLearning provider that offers top-class Java training with an industry-designed course curriculum. Once you complete the training, you will be job-ready and stand out. You will become a highly competent Java developer with the skills employers seek from candidates today.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
Core Java Training | Dec 03 to Dec 18 | View Details |
Pranaya is working as a Content Writer at Mindmajix. She is a technology enthusiast and loves to write about various technologies which include, Java, MongoDB, Automation Anywhere, SQL, Artificial Intelligence, and Big Data. You can connect with her via LinkedIn and Twitter.