Java has been a famous general-purpose programming language for a period of more than 20 years, and it is still relevant today. It is an in-demand programming language that is only increasing in popularity, which indicates that there are several jobs available and job security. Thus, anyone who learns Java will have a rewarding career. This Java Interview Questions blog is prepared to help aspiring Java professionals grasp the Java basics and crack the job interviews. The interview questions cover essential Java topics like Classes, Objects, Loops, operators, access specifiers, control statements, abstraction, encapsulation, constructors, etc. It also includes sample Java programs that can be asked in the job interviews.
Java is a booming technology across the world, and it is a simple and robust language to code and even learn. Code reusability is one of the prominent features of Java which is not possible with the C language. Inheritance is an important concept that is introduced in Java for code reusability.
Java is used everywhere as it is open-source software, and it also provides a platform for many users to perform a specific task effectively. According to Oracle, 3 billion devices run on Java, 3 billion devices run on Java. Some of the applications where Java is used are Access control systems, Automobiles, IoT gateways, optical sensors, and many more.
If you are aspiring to start your career in the field of Java as a developer, then you are in the right place. These days, cracking the Java interview has become more critical due to the increased complexity of the interview process.
Table of Content - Java Interview Questions |
We have gathered a bunch of Frequently Asked Java Interview Questions 2023 over here. These questions would help you stand apart from the crowd and crack the interview very easily. So, let’s get started with the interview questions.
Java is a popular object-oriented programming language. It is defined as a complete collection of objects. By using Java, we can develop lots of applications such as gaming, mobile apps, and websites.
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. |
In the year 1991, a small group of engineers called ‘Green Team’ led by James Gosling, worked a lot and introduced a new programming language called “Java”. This language is created in such a way that it is going to revolutionize the world.
In today’s World, Java is not only invading the internet, but also it is an invisible force behind many of the operations, devices, and applications.
[Related Blog: Java Tutorial]
The differences between C and Java are as follows:
C- Language | Java |
C language was developed by Dennis M. Ritchie in the year 1972. | Java was developed by James Gosling in the year 1995. |
C is Procedural-Oriented | Java is Object-Oriented |
Functions play a major role in the C language. | Objects play a major role in the Java language. |
It is a middle-level language | It is a high-level language. |
C language does not support OOPS Concepts. | Java supports OOPS concepts, in which Inheritance the main property used for code reusability. |
In C, memory is allocated using Malloc | In Java, memory is allocated using a new keyword. |
The threading concept is not supported by C | Java supports Threading |
It is not portable | It is portable |
Default members of C are public | Default members of Java are private |
Storage classes are supported by C | Storage classes are not supported in Java |
Java is the first programming language that is used to write code on a virtual machine, so that is the reason why it is called JVM (Java Virtual Machine). This JVM is a new concept that is introduced in Java. It also provides a new feature called code reusability which is not possible in C.
Java | C++ |
Java is platform-independent | C++ is platform dependent |
The Goto statement is not supported by Java | C++ supports the goto statement |
Multiple inheritances are supported in Java by using interfaces | Multiple inheritances are supported in C++ |
Java doesn’t support structures and unions | C++ does support unions and structures |
Java has built-in support for threading | C++ does not provide built-in support for threading |
Java is used for building applications | C++ is used for system programming |
Java uses both an interpreter and a compiler | C++ uses compiler only |
The following are the notable features of Java:
Class is defined as a template or a blueprint that is used to create objects and also to define objects and methods.
The instance of a class is called an object. Every object in Java has both state and behavior. The state of the object is stored in fields and the behavior of the objects is defined by methods.
[Related Blog: Classes and Objects in Java]
class Mindmajix
{
public static void main(String args[ ]) {
System.out.println("Hello World");
}
}
JVM is the abbreviation for Java Virtual Machine. It is a virtual machine that provides a runtime environment to write code. JVM is a part of JRE (Java Runtime Environment) and is used to convert the bytecode into machine-level language. This machine is responsible for allocating memory.
Top 10 Programming Languages that you need to watch out for to boost your career in 2023
There are totally five memory areas that are allocated by the JVM, and they are:
ClassLoader: class loader is a subschema of JVM which is used to load class files. Whenever we run Java programs, the data will be first loaded from the classloader. There are mainly three in-built classloaders in JVM, they are:
Java Development Kit is one of the three prominent technology packages used in Java programming. JDK is used as a standalone component to run the Java programs by JVM and JRE. This kit is used to implement Java platform specifications, including class libraries and compiler.
Java Runtime Environment (JRE) is a collection of software tools that are designed for the development of Java applications. This is a part of JDK, but it can be downloaded separately. JRE is mainly responsible for orchestrating the component activities.
We can understand the difference between JVM, JDK, and JRE by the following diagram:
[Related Blog: Java stream interview questions]
Just In Time Compiler is the component of JRE, which is used to compile the bytecodes of the particular method into the native machine code. This compiled code of the method is directly called by JVM without interpreting it
Variables in Java can be defined as a basic storage unit of a program. It is a storage unit that holds the value during the program execution. Always the variable is assigned with a datatype.
For Example:
int a = 10;
There are mainly three different types of variables available in Java, and they are:
Static Variables: A variable that is declared with the static keyword is called a static variable. A static variable cannot be a local variable, and the memory is allocated only once for these variables.
Local Variables: A variable that is declared inside the body of the method within the class is called a local variable. A local variable cannot be declared using the static keyword.
Instance Variables: The variable declared inside the class but outside the body of the method is called the instance variable. This variable cannot be declared as static and its value is instance-specific and cannot be shared among others.
Example:
class A{
int num=30;//instance variable
static char name=pranaya;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Typecasting in Java is done explicitly by the programmer; this is done to convert one data type into another data type.
Widening (automatically) - conversion of a smaller data type to a larger data type size.
byte -> short -> char -> int -> long -> float -> double
Narrowing (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Type conversion can be defined as converting one data type to another data type automatically by the compiler.
There are two types of type conversions, and they are:
[ Related Article:- Clojure Tutorial]
Datatypes in Java specify the values and sizes that can be stored in the variables. There are mainly two types of data types; they are:
Primitive data types in Java are the major constituents of data manipulation. These are the most basic data types that are available in Java. The primitive data types include int, char, byte, float, double, long, short, and boolean.
Data Type | Default Size | Default Value |
int | 4 bytes | 0 |
char | 2 bytes | ‘u0000’ |
byte | 1 byte | 0 |
byte | 2 bytes | 0 |
long | 8 bytes | 0L |
float | 4 bytes | 0.0f |
double | 8 bytes | 0.0d |
boolean | 1 bit | false |
The non-primitive data types are something that is different from primitive data types, and these non-primitive data types include String, arrays, and structures.
This is only due to the reason that Java uses the Unicode system. The notation ‘u0000’ is the lowest range of the Unicode system, and it is the default value of the char data type.
The new keyword is used to create an object.
For example:
Mindmajix m1= new Mindmajix();// create an object for Mindmajix.
Unicode is a Universal International Standard Character Encoding which is an adequate resource for representing most of the languages written worldwide.
To overcome the problems present in the previous language standards, the Unicode system has been introduced. Java uses the Unicode system because the character default size provided by Unicode is 2 bytes and Java also needs only 2 bytes for the character.
It is because the Java compiler converts the code into byte code which is the main transitional language between machine code and source code. This byte code is not platform-dependent so that it can be compiled and executed on any platform.
No, they are no such keywords in Java.
Both the compilation and execution of the programs are done correctly because in Java specifiers order doesn’t matter.
No, local variables are not initialized by any default values.
Eight types of operators are available in java, and they are:
Java provides a set of rules and regulations for particularly specifying the order in which operators are evaluated. If the expression has many numbers of operators then the operator precedence comes into action. This operator precedence evaluates the operators present in the expressions based on the priority. For example, multiplication has the highest priority when compared to addition and subtraction.
[Related Blog: Operators In Java]
Operator | Description |
Logical NOT | This operator can be used with logical expressions, boolean type variables, and relational variables, The Logical NOT operator is denoted by the symbol “!” |
Logical OR | These logical operators operate only on boolean variable types and the symbol for this operator is “||” |
Logical AND | We can combine many relational operations using this operator and the output will be of boolean type. The “&&” is the symbol for logical AND |
This type of operator has only one operand and is mainly used to perform various operations including negating an expression, either incrementing/ decrementing the value by one, and invention on boolean values.
An example for the unary operator is given below:
class UnaryExample{
public static void main(String args[]){
int x=15;
System.out.println(x++);//15 (16)
System.out.println(++x);//17
System.out.println(x--);//12 (16)
System.out.println(--x);//15
}}
++a is a prefix increment and a++ is the postfix increment. The prefix increment is used to return the value after incrementing the present value. Whereas in postfix increment, the value is returned before incrementing it.
Left Shift: This left shift is a bitwise operator in which bits are moved towards the left side and zeros are placed at the rightmost places.
Example:
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: 4
Right Shift: It is also of the bitwise operator in which bits are moved towards the right-hand side and zeros are places at the leftmost places.
Example:
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 shfit is: " +a);
System.out.println("the value of a after applying right shfit is: " +i);
}
}
Output: 1
Bitwise operators are mainly used to work on bits and these operators continue to work on bit-by-bit operations.
The following are the bitwise operators in Java, and they are:
Ternary operator in Java is used to replace the if-else statement. The representation or the syntax for the ternary operator is given as:
variable= (expression) ? expression true : expression false
Yes, Java allows us to save our Java file by .java only, we need to compile it by javac.java and run it by Java class name.
For example:
//save by .java only
class A{
public static void main(String args[]){
System.out.println("Hello Mindmajix");
}
}
Java keywords are also called “Reserved keywords” that act as a key to a code. Keywords in Java are predefined that cannot be used as an object name or variable. There are many keywords in Java, and some of them are:
There are four access specifiers present in Java, and they are:
The following are the advantages of packages in Java, and they are:
The program is as follows:
class Java
{
public static void main (String args[])
{
System.out.println(10 * 50 + "Mindmajix");
System.out.println("Mindmajix" + 10 * 50);
}
}
Output:
500Mindmajix
Mindmajix500
In Java control statements are divided into three types. They are:
[Related Blog: Control Statements in Java]
A selection statement is mainly used to transfer program control to a specific flow based upon the condition either true or false. These selection statements are also called conditional statements.
Selection/Conditional statements in Java include:
The iterative statements in Java are also called looping statements, these statements are the set of statements that repeat continuously until the condition for the termination is not met.
Looping/iterative statements in Java include:
In Java, jump statements are mainly used to transfer control to another part of our program depending on the condition. Moreover, these statements are used to jump directly to other statements.
For-each is another kind of array traversing technique in Java which is the same as that of for loop, while loop. It is most commonly used to iterate over a collection or an array such as ArrayList. An example for for-each loop is as follows:
class ForEachPro{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
12
14
44
In the case of a while loop the condition is tested first and then if the condition is true then the loop continues if not it stops the execution. Whereas in the case of the do-while loop first the condition is executed and at the end of the loop, the condition is tested.
The syntax for the while loop is as follows:
while(condition){
//code to be executed
}
Java comments are statements that are not executed by the interpreter and compiler. These are used to provide information about the class, variables, methods, and any statements. Comments are mainly used to hide program code for a specific time.
There are mainly three types of comments in Java, and they are:
OOPs is an abbreviation for Object-Oriented Programming Language which entirely deals with an object. The main aim of OOPs is to implement real-world entities such as objects, classes, inheritance, polymorphism, and so on. Simula is considered the first object-oriented programming language. The most popular programming languages are Java, Python, PHP, C++, and many others.
The following are the OOPs concepts that are included in Java:
In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality.
Binding data and code together into a single unit are called encapsulation. The capsule is the best example of encapsulation.
When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.
Polymorphism in Java provides a way to perform one task in different possible ways. To achieve polymorphism in Java we use method overloading and method overriding. For example, the shape is the task and various possible ways in shapes are triangles, rectangle, circle, and so on.
The following are the advantages of OOPs, and they are:
An object-based programming language provides the most effective way to follow all the features of OOPs concepts except inheritance. VBScript and JavaScript are examples of Object-based programming languages. Whereas Object-oriented programming language supports all the features of OOPs concepts and examples of Object-oriented programming language is Java, Python, and so on.
All the object references in Java are initialized to null.
It is a paradigm entirely based on objects having defined methods in the class to which it belongs. This is mainly used to incorporate the advantages of 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 as follows:
Java naming convention is a rule to be followed for naming your identifiers such as package, variable, method, and constants. These conventions are supported by many Java communities such as Netscape and Sun Microsystems and mostly all the fields of java programming are given according to Java naming conventions.
The rules which we need to follow to declare a class are as follows:
An example for the class is,
public class Thread
{
//code snippet
}
A constructor is a special type of method with a block of code to initialize the state of an object. A constructor is called only when the instance of the object is created. Every time in Java object is created using the new keyword and by default, the constructor is called.
The rules we need to follow while creating a constructor are:
There are two constructors in Java, and they are:
Default constructor: It is also called a no-argument constructor and it is mainly used to initialize the instance variable with the default value. Moreover, it is also used to perform some useful tasks on object creation. This default constructor is implicitly invoked by the compiler if there is no constructor for a particular class.
Parameterized constructor: A parameterized constructor is one type of constructor which is mainly used to initialize the instance variables with the given values. In simple words, the constructor that accepts arguments is called a parameterized constructor.
An example of a default constructor is as follows:
//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: Welcome to Mindmajix
An example of the parameterized constructor is as follows:
//Java Program to demonstrate the use of the parameterized constructor.
class Training{
int id;
String name;
//creating a parameterized constructor
Training(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
Training t1 = new Training(111,"DevOps");
Student4 s2 = new Student4(222,"Oracle");
//calling method to display the values of object
t1.display();
t2.display();
}
}
Output:
111 DevOps
222 Oracle
Yes, the constructor will return the current or present instance of the class.
No, the constructor cannot be inherited.
Yes, It is possible to overload a constructor by changing the number of arguments for each constructor in a particular program or it is possible to overload a constructor by changing the parameter data types.
No, We can not declare the constructor as final, if we declare it as final compiler throws a “modified final not allowed” error.
Yes, there is a class called Constructor class available in Java. The purpose of the Constructor class is to get the internal information of the constructor in the class. It is present in java.lang.reflect package.
Related Article JSP Interview Questions and Answers |
There is no copy constructor in Java, we can copy the values from one object to another same as that of a copy constructor in C++. In Java, there are many ways to copy the values of one object to another and they are:
In Java method is defined as a set of code that is represented by a name and can be invoked at any point in a program with the help of the method name. Each and every method in the program has its own name which is not the same as that of a class name.
The difference between constructor and method are as follows:
Constructor | Method |
The constructor should have the same name as the class name | The method name is not the same as that of the class name |
A constructor has no return type | The method must have a return type |
It can be invoked implicitly | It can be invoked explicitly |
The constructor is used to initialize the state of the object | A method is used to expose the behavior of an object |
Default constructor can be provided by the compiler | The default method is not provided by the Java compiler |
In Java method signature is given the specified format followed by the method name, type, and order of its parameters. Exceptions are not considered as a part of the method signature.
return-type method name (parameter list)
{
//code
}
Keyword static in Java is mainly used for memory management and we can declare block, variable, method, and nested class as static.
In Java, we can declare a variable as static, if we declare any variable as static the following can be done, and they are:
Example for static variable:
//Program of static variable
class Mindmajix1{
int ID;
String employee name;
static String office ="Appmajix";
Mindmajix1(int i,String n){
ID = i;
employee name = n;
}
void display ()
{
System.out.println(ID+" "+name+" "+office);}
public static void main(String args[]){
Mindmajix1 m1 = new Mindmajix1(346,"Pranaya");
Mindmajix1 m2 = new Mindmajix1(222,"Lilly");
m1.display();
m2.display();
}
}
Output:
346 Pranaya Appmajix
222 Lilly Appmajix
If we declare a method as static, the following operations take place, and they are:
The restrictions that we face if we declare a method as static are:
The main reason is that the object is not required to call for a static method so, if we declare the main method as non-static we need to create an object first and then call the main() method. In order to save memory, we declare the main method as static in Java.
No, we can’t override the static method in Java.
Static block in Java is mainly used to initialize the static data members. The specialty of the static block is that it is executed before the main method at the time of class loading.
An example of the static block is as follows:
Class Mindmajix{
static{System.out.println("static block");
}
public static void main(String args[]){
System.out.println("Hello World");
}
}
Output:
static block
Hello World
Yes, we can execute the program in Java without the main method using a static block. It was possible only till JDK 1.6 and from JDK 1.7 it is not possible to execute the program without the main method in Java.
The program will be compiled, but at runtime, it throws NoSuchMethodError error.
As we know that the static context is suitable for only class, variable, and method, not for the object. So the constructors are invoked only when an object is created, so there is no possibility to declare the constructor as static in Java.
No, if we declare abstract methods as static it becomes a part of the class, and we can directly call it which is not required. Calling an undefined method is unnecessary. Therefore declaring an abstract method as static is not allowed.
Yes, as we know that 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 abstract class name. Consider the following example.
abstract class Check
{
static int i = 113;
static void CheckMethod()
{
System.out.println("hi, how are you");
}
}
public class CheckClass extends Check
{
public static void main (String args[])
{
Check.CheckMethod();
System.out.println("i = "+Check.i);
}
}
Output:
hi, how are you
i = 113
The main use of this keyword is to refer to the current object in Java programming.
The following are the usage provided by this keyword in Java, and they are:
Yes, this keyword is used to refer to the current class instance variable and it is also used to initiate or invoke the current class constructor.
An object class is a superclass for all the classes in Java.
Singleton class can be defined as the class that consists of only one single instance. In this class, all the methods and variables belong to only one instance. Singleton class is mainly used in a situation where we need to limit the objects for a class.
In Java, we use inheritance mainly for two uses, and they are:
The syntax for inheritance in Java is as follows:
class Superclass extends subclass
{
//code
}
By using the Math.random() method we can generate random numbers in Java ranging from 0.1 to less than 1.0. Moreover, the random numbers can be generated by using the Random class present in java. util package.
The main() method in Java doesn’t return any data because it is declared with a void return type.
In Java, the package is defined as a collection of interfaces and classes that are bundled together and related to each other. Usage of packages in the program will help developers to group the code for proper re-use. In Java, packages are used by importing them into different classes.
Java doesn’t support multiple inheritances in order to reduce the complexity and simplify the language. An example of multiple inheritances in Java is given below:
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:
Compile-time error
So, the above example shows that Java doesn’t support multiple inheritances.
In Java, main() method must be always public static to run any application or program correctly. Suppose, if the main method is declared as private there will be no complications but it will give a runtime error.
Yes, the classes present in Java can have multiple constructors with different parameters.
If a class in Java has multiple numbers methods with the same name and different parameters, then it is called as method overloading. The main advantage of method overloading is that it increases the readability score of a program.
There are two different ways to overload a method, and they are:
class Addition{
static int add(int x,int y)
{
return x+y;
}
static int add(int x,int y,int z)
{
return x+y+z;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(10,20));
System.out.println(Adder.add(10,20,30));
}}
Output:
30
60
class Addition{
static int add(int x, int y)
{
return x+y;
}
static double add(double x, double y)
{
return x+y;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(22,22));
System.out.println(Adder.add(12.5,12.5));
}}
Output:
44
25
Ambiguity is the main reason why method overloading is not possible by changing the return type of method only.
Yes, we can overload the main() method in Java by using method overloading but, JVM only calls the main() method that receives string array as arguments only.
If the subclass in the program has the same method as declared in superclass then it is known as method overriding.
Method overriding is used to achieve run-time polymorphism and also it is used to provide a specific implementation for a method that is already given by its subclass.
The rules are as follows:
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
Class Shape{
//defining a method
void run()
{
System.out.println("Shape is ready");
}
}
//Creating a child class
class Rectangle extends Shape{
//defining the same method as in the parent class
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:
Rectangle is drawn
No, a static method cannot be overridden, it is because a static method is bounded with a class and an instance method is bounded with an object. So, the static belongs to the class area whereas, the instance method belongs to the heap area.
No, because the main() method is static.
Aggregation is built to represent the weak relationship whereas, the composition is built to represent the strong relationship.
Pointer is a variable that mainly refers to the memory address. Java doesn’t support pointers because they are complex to understand and unsecured.
Super keyword in Java is used to conjure immediate prompt parent class object. It is also called a reference variable.
The uses of the super keyword in Java are as follows:
Yes, all the functions in Java are virtual by default.
Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!
Name | Dates | |
---|---|---|
Core Java Training | Dec 09 to Dec 24 | View Details |
Core Java Training | Dec 12 to Dec 27 | View Details |
Core Java Training | Dec 16 to Dec 31 | View Details |
Core Java Training | Dec 19 to Jan 03 | 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.
1 / 15
Copyright © 2013 - 2023 MindMajix Technologies